Show problems as
Classic problem #1769MediumArrayStringPrefix Sum

Minimum Number of Operations to Move All Balls to Each Box

Real-world version: Gathering the Crates Into Every Bay
Tracked in this browser only
Read Minimum Number of Operations to Move All Balls to Each Box on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A corridor has bays in a row, given by bays, where 1 marks a bay holding a crate and 0 marks an empty bay.

One step shifts a crate to a bay next door. A bay may hold any number of crates at once.

Return a list whose entry i is the fewest steps needed to gather every crate into bay i, each entry worked out on its own as though the corridor had never been touched.

Examples

Example 1

Input
bays = "1001"
Output
[3, 3, 3, 3]

Two crates stand three bays apart. Gathering them into any bay of the corridor always comes to three steps, since every step towards one is a step away from the other.

Example 2

Input
bays = "111"
Output
[3, 2, 3]

For the middle bay the two outer crates move one step each and the crate already there moves none. For either end bay the crates move one and two steps.

Example 3

Input
bays = "10"
Output
[0, 1]

The crate already sits in the first bay, so nothing moves, and reaching the second bay takes one step.

Constraints

  • 1 <= bays.length <= 2000
  • every character of bays is 0 or 1

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def min_operations(bays: str) -> list[int]:
Java
public int[] minOperations(String bays)