#2270

Number of Ways to Split Array

Medium
ArrayPrefix SumPrefix SumTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

By calculating the total sum once and using a running sum for the left part, we can efficiently determine valid splits without recalculating sums repeatedly.

⚙️

Algorithm

6 steps
  1. 1Step 1: Calculate the total sum of the array.
  2. 2Step 2: Initialize a variable for the left sum and a count for valid splits.
  3. 3Step 3: Loop through the array up to n-2, updating the left sum at each step.
  4. 4Step 4: For each index, calculate the right sum as total_sum - left_sum and check the condition.
  5. 5Step 5: Increment the count if the condition is satisfied.
  6. 6Step 6: Return the count of valid splits.
solution.py15 lines
1# Full working Python code
2
3def count_valid_splits(nums):
4    total_sum = sum(nums)
5    left_sum = 0
6    count = 0
7    for i in range(len(nums) - 1):
8        left_sum += nums[i]
9        right_sum = total_sum - left_sum
10        if left_sum >= right_sum:
11            count += 1
12    return count
13
14# Example usage
15print(count_valid_splits([10, 4, -8, 7]))  # Output: 2

Complexity note: This complexity is achieved by calculating the total sum once and using a single pass to find valid splits, leading to O(n) time.

  • 1Understanding prefix sums can simplify many problems involving array splits.
  • 2Using a single pass to calculate sums can significantly improve efficiency.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.