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
Minimum Operations to Move All Balls to Each BoxInput: boxes = "110"110Position 0Position 1Position 2↓ Calculate operations for each position ↓113Move ball from pos 1Move ball from pos 0Move both ballsOutput: [1, 1, 3]Each number represents minimum operations to move all balls to that position
Understanding the Visualization
1
Input
Binary string representing boxes with balls
2
Process
Calculate minimum operations to move all balls to each position
3
Output
Array of operation counts for each position
Key Takeaway
🎯 Key Insight: Use two passes to calculate left and right ball contributions separately, avoiding redundant distance calculations
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