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.
Return the number of seconds needed to complete this process.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= s.length <= 1000
s[i]
is either'0'
or'1'
.
Follow up:
Can you solve this problem in O(n) time complexity?
Solution
Method 1 – Greedy Simulation (O(n))
Intuition
Track the number of 1’s to the left of each 0, and for each 0, compute how many steps it takes to move past all 1’s to its left. The answer is the maximum such value.
Approach
Iterate through the string, for each 0, count how many 1’s have been seen so far. The time for this 0 is the maximum of (previous time + 1) and the number of 1’s seen so far. The answer is the maximum time for any 0.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(1)