NeetCode #130LC-2270MediumArrays & Hashing
← Back to All Problems#130 · #2270 · Number of Ways to Split Array(分割数组的方案数)
📌 Problem Statement & Constraints
Given an array
nums, count the number of ways to split it into two non-empty parts such that the sum of the first part is at least the sum of the second part. Constraints: 2 <= nums.length <= 10^5, -10^5 <= nums[i] <= 10^5.💡 Core Algorithmic Approaches
- Compute the total sum once, then sweep the split point while maintaining the left sum.
- At split index
i(the first part beingnums[0..i]), the condition isleft >= total - left. - Count the splits satisfying it. The split point only ranges over
0..n-2so both parts are non-empty. - Avoid recomputing
sum(nums[:i])inside the loop, which would be O(n^2).
💻 Benchmark Python3 Implementation
class Solution:
def waysToSplitArray(self, nums: List[int]) -> int:
total = sum(nums)
left = 0
res = 0
for i in range(len(nums) - 1): # the right part must be non-empty
left += nums[i]
if left >= total - left: # left sum at least the right sum
res += 1
return res⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one pass for the total and one for the splits.
💾 Space Complexity
O(1): two accumulators.
⚠️ Interview Pitfalls & Follow-ups
- Using
>instead of>=: the condition is *at least*, so equality counts. - Including
i == n - 1: the right part would be empty, which is not a valid split. - Recounting the prefix sum each iteration: O(n^2); maintain it incrementally.
- Assuming all values are non-negative: the constraints allow negatives, so the left sum is not monotone -- but the direct comparison still works because we simply test every split.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Arrays & Hashing Problems
中文速览与面试要点
分割数组的方案数
给你一个下标从 0 开始长度为 n 的整数数组 nums。如果以下条件满足,我们称这些分割是 有效 的: nums 在下标 i 处被分割成 nums[0..i] 和 nums[i+1..n−1] 两部分(0 ≤ i < n−1); nums[0..i] 中元素之和大于等于 nums[i+1..n−1] 中元素之和。请你返回有效分割的总数。约束:2 ≤ nums.length ≤ 10^5;-10^5 ≤ nums[i] ≤ 10^5。
核心要点
- 前缀和 + 滚动(标准解) :先求数组总和 total,然后从左往右累加左半和 left。
- 判定条件 :位置 i 处有效当且仅当 left >= total - left 。
- 为什么用 total - left :右半和无需重新求和,直接由总和减去左半和得到,O(1) 完成。
- 遍历范围 :i 从 0 到 n−2,保证两部分都非空。
常见陷阱
- 遍历范围写成 range(len(nums)) :i = n−1 时右半为空,不满足「两部分都非空」的约束。
- 每个位置重新求右半和 :退化为 O(n²)。必须用 total - left 。
- 先判定后累加的顺序搞反 : left 应包含 nums[i] (因为左半是 nums[0..i] ),因此必须先 left += nums[i] 再判定。
- 担心负数 :nums 可含负数,但判定条件 left >= total - left 对负数同样成立,无需特殊处理。
参考实现
class Solution:
def waysToSplitArray(self, nums: list[int]) -> int:
total = sum(nums)
left = 0
ans = 0
for i in range(len(nums) - 1): # 两部分都非空
left += nums[i]
if left >= total - left: # 左半和 >= 右半和
ans += 1
return ans