Ctrl K

Gather the Balls in Each Box

Medium
A row of boxes is described by the string boxes: boxes[i] is '1' if box i holds one ball and '0' if it is empty. In one move you can shift a single ball into a neighbouring box. A box may hold any number of balls. For every box i, work out the fewest moves needed to bring all the balls into it, always starting from the original layout. Return these numbers as a list.
Example 1
boxes="1001" → [3, 3, 3, 3]

The balls sit in boxes 0 and 3. For any box between them the two balls travel 3 moves in total.

Example 2
boxes="0110" → [3, 1, 1, 3]

Gathering in box 0 costs 1 + 2 = 3 moves; gathering in box 1 needs just one move for the neighbouring ball.

Constraints
  • 1 ≤ len(boxes) ≤ 10⁵
  • Every character of boxes is '0' or '1'
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsRoll Letters by Prefix MediumPalindrome After a Few Fixes MediumBooks Between Bookends MediumRoll Letters by Ranges MediumRecycling Truck Minutes Medium
loading Python…
Input
boxes="1001"
Expected
[3, 3, 3, 3]

Run checks the first 3 tests in your browser. Submit checks all 87 tests on the server, hidden ones included.