NeetCode #103LC-1769MediumArrays & Hashing
← Back to All Problems#103 · #1769 · Minimum Number of Operations to Move All Balls to Each Box(移动所有球到每个盒子所需的最小操作数)
📌 Problem Statement & Constraints
You have
n boxes given as a binary string boxes, where boxes[i] == '1' means box i contains a ball. In one operation you may move one ball to an adjacent box. Return an array where answer[i] is the minimum number of operations to move all balls to box i. Constraints: 1 <= boxes.length <= 2000.💡 Core Algorithmic Approaches
- The cost to gather all balls at position
idecomposes into contributions from the left and from the right. - Sweep left to right, maintaining the number of balls seen so far and the running cost of bringing them all to the current position.
- The recurrence is
ops += balls_seen, thenballs_seen += boxes[i]-- each additional step moves every ball seen so far one more box. - Repeat the sweep right to left and add the two contributions. This is the classic two-pass prefix technique.
💻 Benchmark Python3 Implementation
class Solution:
def minOperations(self, boxes: str) -> List[int]:
n = len(boxes)
res = [0] * n
# left-to-right contribution
cnt = ops = 0
for i in range(n):
res[i] += ops # cost of bringing left balls here
cnt += int(boxes[i])
ops += cnt # next position costs one more per ball
# right-to-left contribution
cnt = ops = 0
for i in range(n - 1, -1, -1):
res[i] += ops
cnt += int(boxes[i])
ops += cnt
return res⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): two linear sweeps.
💾 Space Complexity
O(1) beyond the output array.
⚠️ Interview Pitfalls & Follow-ups
- Updating
opsbeforecnt: the order matters -- add the cost for the current position first, then absorb the current box's ball, so the next position accounts for it. - Recomputing the cost per index with a nested loop: O(n^2), which is 4 * 10^6 here and still passes, but the two-pass version is O(n).
- Using the raw character
boxes[i]as an integer:'0'is truthy as a string; convert withint()or compare to'1'. - Only doing one direction: both left and right contributions are needed.
⚡
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
中文速览与面试要点
移动所有球到每个盒子所需的最小操作数
有 n 个盒子,给你一个长度为 n 的二进制字符串 boxes,其中 boxes[i] 为 0 表示第 i 个盒子是空的,为 1 表示盒子里有一个小球。在一步操作中,你可以将一个小球从一个盒子移动到相邻的盒子。返回一个长度为 n 的数组 answer,其中 answer[i] 是将所有小球移动到第 i 个盒子所需的 最小操作数 。约束:n == boxes.length;1 ≤ n ≤ 2000;boxes[i] 为 0 或 1。
核心要点
- 两次扫描 + 增量累积(标准解) :一次从左往右、一次从右往左,各自维护「已遇到的球数 cnt」与「累积代价 ops」。
- 增量递推 :遍历到位置 i 时, answer[i] += ops (把左侧所有球搬到 i 的代价)。随后若 boxes[i] == 1 则 cnt += 1 ,再令 ops += cnt (左侧所有球各自多移动一步)。
- 为什么两次扫描能覆盖全部 :左扫描只统计左侧的球对 i 的贡献,右扫描统计右侧的贡献,相加即为全部球到 i 的总代价。
- 为什么比暴力快 :暴力对每个 i 都遍历全部球是 O(n²);增量法利用「相邻位置的代价只差一个球数」这一递推关系,把单次降到 O(1)。
常见陷阱
- ops += cnt 与 cnt += 1 的顺序搞反 :必须先累加 ops (用旧的 cnt),再更新 cnt。顺序颠倒会导致位置 i 上的球被错误地计入「已在左侧」而多算一步。
- 只做一次扫描 :只从左往右扫只能统计左侧球的贡献,会漏掉右侧球。必须双向。
- 对每个位置暴力遍历所有球 :O(n²) 在 n = 2000 时约 4 × 10^6 次操作,虽可过但失去了增量递推的考点。
- 误以为要模拟每一步移动 :题目只问操作数,不需要模拟过程。
参考实现
class Solution:
def minOperations(self, boxes: str) -> list[int]:
n = len(boxes)
res = [0] * n
cnt = ops = 0
for i in range(n): # 左侧的球搬到 i
res[i] += ops
if boxes[i] == '1':
cnt += 1
ops += cnt # 已累积的球各自再移动一步
cnt = ops = 0
for i in range(n - 1, -1, -1): # 右侧的球搬到 i
res[i] += ops
if boxes[i] == '1':
cnt += 1
ops += cnt
return res