Minimum Number of Operations to Move All Balls to Each Box
You have n boxes in a row, given as a binary string boxes where boxes[i] is '1' if box i holds one ball and '0' if it is empty. One operation moves a single ball to an adjacent box. Return an array answer where answer[i] is the minimum number of operations needed to move every ball into box i, computed for each box independently from the original layout.
30:00
Minimum Number of Operations to Move All Balls to Each Box
You have n boxes in a row, given as a binary string boxes where boxes[i] is '1' if box i holds one ball and '0' if it is empty. One operation moves a single ball to an adjacent box. Return an array answer where answer[i] is the minimum number of operations needed to move every ball into box i, computed for each box independently from the original layout.
Example 1:
Input: {"boxes":"110"}
Output: [1,1,3]
Constraints:
n==boxes.length
1≤n≤2000
boxes[i] is either '0' or '1'
Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result
Run code to see results.
Input
arr ={"boxes":"110"}
3 boxes hold 2 balls; each box needs the total distance every ball must travel to reach it.
sweep
ready
balls carried
0
moves
0
boxes in a row
box
0
1
2
left
·
·
·
right
·
·
·
answer
·
·
·
Each step right adds the number of balls already carried to moves, so a box learns its whole left-side cost in O(1); the return sweep does the same for the right side.