Separate Black and White Balls
Real-world version: Sorting the Drum RackThe statement here is our own: the same inputs, outputs and technique.
A loading rack holds n drums in a row, given as the string s. The character '0' is a light drum and '1' is a heavy drum.
In one move you pick two drums that sit next to each other and exchange their positions.
The rack is safe once every light drum sits somewhere to the left of every heavy drum. Return the smallest number of moves that makes the rack safe.
Examples
Example 1
- Input
- s = "1100"
- Output
- 4
One route is `1100` -> `1010` -> `1001` -> `0101` -> `0011`, which is four moves and leaves both light drums left of both heavy drums.
Example 2
- Input
- s = "111000"
- Output
- 9
Each of the three light drums has to travel past each of the three heavy drums, and nine moves reach `000111`.
Example 3
- Input
- s = "0000"
- Output
- 0
There is no heavy drum at all, so the rack is already safe.
Constraints
- 1 <= n == s.length <= 10^5
- s[i] is either '0' or '1'.
- The answer never exceeds 2.5 * 10^9.
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 minimum_steps(s: str) -> int:public long minimumSteps(String s)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 14 test cases: 14 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
More on the same topics
- Valid Palindrome IIReal-world version: Mosaic Border InspectionEasy
- Partition LabelsReal-world version: Duty Roster BlocksMedium
- Find the Lexicographically Smallest Valid SequenceReal-world version: Cheapest Probe Slots On A ReelMedium
- Minimum Number of Swaps to Make the String BalancedReal-world version: Balance the Clamp TapeMedium