Minimum Number of Operations to Move All Balls to Each Box
Real-world version: Gathering the Crates Into Every BayThe 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.
def min_operations(bays: str) -> list[int]:public int[] minOperations(String bays)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 15 test cases: 15 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's