We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Number of Ways to Split Array

Number: 2358

Difficulty: Medium

Paid? No

Companies: Google, Amazon, Microsoft


Problem Description

Given an integer array nums, a split at index i (0 <= i < n-1) is considered valid if the sum of the first i+1 elements is greater than or equal to the sum of the remaining elements. The task is to count the number of such valid splits in the array.


Key Insights

  • Calculate the total sum of the array to determine the sum of the right part for any split.
  • Use a prefix sum to incrementally compute the sum of the left segment.
  • For each possible split position (from index 0 to n-2), check if the left sum is at least as large as the right sum (totalSum - leftSum).
  • Iterating only once through the array leads to an optimal solution.

Space and Time Complexity

Time Complexity: O(n) because we iterate through the array once to compute the prefix sum and check each split. Space Complexity: O(1), aside from the input array, as we only use a few extra variables.


Solution

We begin by computing the total sum of the array. Then, maintain a running prefix sum as we iterate over the array (up to the second-to-last element). At each iteration, the right part's sum is computed as totalSum - leftSum. If leftSum >= rightSum, we increment our count of valid splits. This approach uses a single pass through the array, making it efficient in both time and space. The key data structure is the array itself, and the algorithm leverages the prefix sum method.


Code Solutions

# Python solution with detailed comments
def waysToSplit(nums):
    # Calculate the total sum of the array elements
    total_sum = sum(nums)
    left_sum = 0  # Running prefix sum for the left part
    valid_splits = 0  # Counter for valid splits

    # Iterate through the array up to the second-to-last element
    for i in range(len(nums) - 1):
        left_sum += nums[i]  # Update prefix sum
        right_sum = total_sum - left_sum  # Calculate sum of right part
        # Check if the split is valid: left sum is greater than or equal to right sum
        if left_sum >= right_sum:
            valid_splits += 1

    return valid_splits

# Example usage
print(waysToSplit([10, 4, -8, 7]))  # Output: 2
← Back to All Questions