Minimum Number of Operations to Move All Balls to Each Box - Problem

You have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith box is empty, and '1' if it contains one ball.

In one operation, you can move one ball from a box to an adjacent box. Box i is adjacent to box j if abs(i - j) == 1. Note that after doing so, there may be more than one ball in some boxes.

Return an array answer of size n, where answer[i] is the minimum number of operations needed to move all the balls to the ith box.

Each answer[i] is calculated considering the initial state of the boxes.

Input & Output

Example 1 — Basic Case
$ Input: boxes = "110"
Output: [1,1,3]
💡 Note: For position 0: move ball from pos 1 (1 op). For position 1: move ball from pos 0 (1 op). For position 2: move balls from pos 0,1 (2+1=3 ops).
Example 2 — More Balls
$ Input: boxes = "001011"
Output: [11,8,5,4,3,4]
💡 Note: Position 0: balls at 2,4,5 need 2+4+5=11 ops. Position 1: balls need 1+3+4=8 ops. And so on for each position.
Example 3 — Single Ball
$ Input: boxes = "1"
Output: [0]
💡 Note: Only one box with one ball - no operations needed to move all balls to position 0.

Constraints

  • n == boxes.length
  • 1 ≤ n ≤ 2000
  • boxes[i] is either '0' or '1'

Visualization

Tap to expand
Move All Balls to Each Box INPUT boxes = "110" i=0 i=1 i=2 '1' '1' '0' = Ball (value '1') = Box Goal: For each position i, find min operations to move all balls to box i Operation: Move 1 ball to adjacent box (cost = 1) ALGORITHM STEPS 1 Left-to-Right Pass Track balls and ops from left 2 Right-to-Left Pass Track balls and ops from right 3 Combine Results Sum left + right operations 4 Return Answer O(n) time, O(1) extra space Calculation for "110": i=0: 0 + 1*1 + 2*0 = 1 i=1: 1*1 + 0 + 1*0 = 1 i=2: 2*1 + 1*1 + 0 = 3 Formula: sum of |j-i| for all j where boxes[j] == '1' FINAL RESULT Operations to move all balls 1 1 3 i=0 i=1 i=2 Output: [1, 1, 3] answer[0] = 1 Move ball from box 1 to 0 answer[1] = 1 Move ball from box 0 to 1 answer[2] = 3 Move 2 balls (2+1 steps) Key Insight: Use prefix sums! As we move from position i to i+1, all balls on the left need 1 more operation, and all balls on the right need 1 less operation. This transforms O(n^2) brute force into O(n) optimal. TutorialsPoint - Minimum Number of Operations to Move All Balls to Each Box | Optimal Solution
Asked in
Facebook 15 Google 12 Amazon 8
28.5K Views
Medium Frequency
~15 min Avg. Time
845 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen