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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code