Time Needed to Rearrange a Binary String - Problem

You are given a binary string s. In one second, all occurrences of "01" are simultaneously replaced with "10".

This process repeats until no occurrences of "01" exist in the string.

Return the number of seconds needed to complete this process.

Input & Output

Example 1 — Basic Case
$ Input: s = "0110"
Output: 2
💡 Note: Second 1: "0110" → "1001" (replace 01 with 10). Second 2: "1001" → "1010" → "1100". No more "01" patterns exist, so 2 seconds total.
Example 2 — Single Swap
$ Input: s = "01"
Output: 1
💡 Note: Second 1: "01" → "10". No more "01" patterns, so 1 second total.
Example 3 — No Swaps Needed
$ Input: s = "1100"
Output: 0
💡 Note: Already sorted with all 1's before 0's. No "01" patterns exist, so 0 seconds needed.

Constraints

  • 1 ≤ s.length ≤ 1000
  • s[i] is either '0' or '1'

Visualization

Tap to expand
Binary String Rearrangement ProcessInitial State0110"0110"After 1 Second1001"1001"After 2 Seconds1100"1100"Key InsightEach "1" will move past all "0"s to its rightCount zeros to right of each "1"Maximum count = answerResult: 2 seconds needed
Understanding the Visualization
1
Input Analysis
Binary string with '01' patterns that need rearranging
2
Transformation
All '01' become '10' simultaneously each second
3
Final State
Count total seconds until no '01' patterns remain
Key Takeaway
🎯 Key Insight: Count how many zeros each 1 needs to pass through - the maximum determines the total time
Asked in
Google 15 Facebook 12
23.4K Views
Medium Frequency
~15 min Avg. Time
892 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