Time Needed to Rearrange a Binary String Problem
#2380
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2380.
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.
Example 1:
Input: s = "0110101"
Output: 4
Explanation:
After one second, s becomes "1011010".
After another second, s becomes "1101100".
After the third second, s becomes "1110100".
After the fourth second, s becomes "1111000".
No occurrence of "01" exists any longer, and the process needed 4 seconds to complete,
so we return 4.
Example 2:
Input: s = "11100"
Output: 0
Explanation:
No occurrence of "01" exists in s, and the processes needed 0 seconds to complete,
so we return 0.
Constraints:
1 <= s.length <= 1000s[i]is either'0'or'1'.
Follow up:
Can you solve this problem in O(n) time complexity?
Solution
Approach: Simulation
Every second, all occurrences of "01" are replaced by "10" at the same time. That is exactly what replacing every "01" in the string does in one pass, so we repeat the replacement until no "01" remains and count the rounds.
Each round moves every 1 that has a 0 right before it one step to the left, so there are at most about n rounds.
Complexity: time O(n^2), space O(n), where n is the length of s.
class Solution:
def secondsToRemoveOccurrences(self, s: str) -> int:
ans = 0
while s.count('01'):
s = s.replace('01', '10')
ans += 1
return ans