Show problems as
Classic problem #2380MediumStringDynamic ProgrammingSimulation

Time Needed to Rearrange a Binary String

Real-world version: Beads Sliding Left
Tracked in this browser only
Read Time Needed to Rearrange a Binary String on LeetCode(opens in a new tab)

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

A groove holds a row of tiles described by s, read from left to right. The character '1' is a bead and '0' is an empty tile.

Every second, all beads move at the same instant: a bead whose immediate left neighbour is an empty tile slides into that tile, and every other bead stays put. Since the moves are simultaneous, whether a bead slides is decided by the layout at the start of the second, not by what its neighbours do during it.

Return the number of seconds after which no bead has an empty tile immediately to its left. If the groove already looks like that, return 0.

Examples

Example 1

Input
s = "0011"
Output
3

The groove goes `0011` -> `0101` -> `1010` -> `1100`. After the third second no bead has an empty tile on its left.

Example 2

Input
s = "1010"
Output
1

The groove goes `1010` -> `1100`, so one second is enough: the bead at position 3 slides into position 2 while the bead at position 0 has no empty tile on its left.

Example 3

Input
s = "1111"
Output
0

There is no empty tile at all, so no bead can ever slide.

Constraints

  • 1 <= s.length <= 1000
  • s[i] is either '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 seconds_to_remove_occurrences(s: str) -> int:
Java
public int secondsToRemoveOccurrences(String s)