All problems
0611MediumTwo PointersStringGreedy

Sorting the Drum Rack

Tracked in this browser only
Write code

Trains the technique from

LeetCode 2938Separate Black and White Balls

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def minimum_steps(s: str) -> int:
Java
public long minimumSteps(String s)
September 7
Apply