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
Time Needed to Rearrange a Binary String INPUT Binary String s = "0110" 0 idx 0 1 idx 1 1 idx 2 0 idx 3 Simulation Process: t=0: "0110" 01 t=1: "1010" 01 t=2: "1100" No "01" Zero Positions: Index 0: zero at pos 0 Index 3: zero at pos 3 ALGORITHM STEPS (Count Zeros Approach) 1 Initialize seconds = 0, zeros = 0 2 Traverse String Scan left to right 3 Count Zeros If '0': zeros++ 4 Update Seconds If '1' and zeros > 0: sec = max(sec+1, zeros) Iteration Table i char zeros seconds 0 '0' 1 0 1 '1' 1 1 2 '1' 1 2 3 '0' 2 2 FINAL RESULT Final State: All 1s before 0s 1 1 0 0 "1100" OUTPUT 2 seconds needed Verification: t=0: "0110" --> "1010" t=1: "1010" --> "1100" t=2: Done! [OK] Key Insight: Each '1' that has zeros to its left needs time to "bubble" past all those zeros. The count zeros approach tracks how many zeros each '1' must pass. For each '1', we take max(current_seconds + 1, zeros) because swaps happen simultaneously, but each '1' needs at least one more second than the previous. TutorialsPoint - Time Needed to Rearrange a Binary String | Count Zeros Approach
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