Time Needed to Rearrange a Binary String - Problem
Transform Binary String Through Bubble Swapping

You are given a binary string s containing only '0' and '1' characters. Your goal is to determine how long it takes for all the '1's to "bubble up" to the right side of the string.

The transformation follows a specific rule: In each second, all occurrences of the pattern "01" are simultaneously replaced with "10". This process continues until no more "01" patterns exist in the string.

Example:
"0110" โ†’ "1010" โ†’ "1100"
This takes 2 seconds to complete.

Return the minimum number of seconds needed to complete this rearrangement process.

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "0110"
โ€บ Output: 2
๐Ÿ’ก Note: After 1 second: "0110" โ†’ "1010". After 2 seconds: "1010" โ†’ "1100". No more "01" patterns exist, so we return 2.
example_2.py โ€” No Transformation Needed
$ Input: s = "11100"
โ€บ Output: 0
๐Ÿ’ก Note: The string already has all '1's before all '0's, so no transformations are needed. Return 0.
example_3.py โ€” Multiple Swaps
$ Input: s = "010110"
โ€บ Output: 3
๐Ÿ’ก Note: Second 1: "010110" โ†’ "100110" โ†’ "101100". Second 2: "101100" โ†’ "110100" โ†’ "111000". Second 3: "111000" (done). Total: 3 seconds.

Visualization

Tap to expand
Bubble Sort VisualizationWater Tank - Second 0: "0110"0110Water Tank - Second 1: "1010"1010Water Tank - Second 2: "1100" (Final)1100โœ… All bubbles have risen!Mathematical Insight: Count zeros to the right of each '1'
Understanding the Visualization
1
Initial Setup
Identify all '1' bubbles and '0' heavy particles in the string
2
Simultaneous Swapping
In each second, all adjacent '01' pairs swap to become '10'
3
Calculate Mathematically
Instead of simulation, calculate how many '0's each '1' needs to pass
4
Account for Timing
Use max(time + 1, zeros) to handle sequential movement timing
Key Takeaway
๐ŸŽฏ Key Insight: Instead of simulating each second, calculate the maximum time any '1' needs to reach its final position by counting the zeros to its right and accounting for sequential movement timing.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through the string from right to left

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using a few variables to track counts and time

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค s.length โ‰ค 105
  • s consists only of characters '0' and '1'
  • The string is guaranteed to be non-empty
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
28.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen