< Back





2270. Number of Ways to Split Array

Not sure how this is a Medium problem, but here goes. Array of integers, we want to find all valid
splits, being that the sum of array[0:i] is greater than or equal to array[i:n-1]. We do this by
maintaining a running total valid splits, a sum for the left side of the array, and a sum for the
entire array.

We iterate through the array until n-1, adding the value of the current element of the array to the
left-hand total. We subtract the value of the left-hand total from the total sum of the array, and
if the left-hand total is greater than or equal to this difference, we have found a valid split.

The solution is as follows:


  class Solution:
      def waysToSplitArray(self, nums: List[int]) -> int:
          ans = left = 0
          total = sum(nums)

          for i in range(len(nums) - 1):
              left += nums[i]
              right = total - left
              if left >= right:
                  ans += 1

          return ans


_ Time Complexity:

  O(n) - We traverse the array once.

_ Space Complexity:

  O(1) - We use constant space to store our answer.