Time Needed to Rearrange a Binary String

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.

Return the number of seconds needed to complete this process.

Follow up: Can you solve this problem in O(n) time complexity?

Example 1
Inputs = "0110101"
Output4
After four seconds, s becomes "1111000", with no occurrence of "01" remaining, so the process takes 4 seconds.
Example 2
Inputs = "11100"
Output0
No occurrence of "01" exists in s, so the process takes 0 seconds.

Constraints

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

Asked at 5 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate