{x}
blog image

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.

 

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 <= 1000
  • s[i] is either '0' or '1'.

 

Follow up:

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

Solution Explanation for Time Needed to Rearrange a Binary String

This problem asks to find the number of seconds needed to rearrange a binary string s such that no "01" subsequences exist. The rearrangement happens by simultaneously replacing all occurrences of "01" with "10".

Approach 1: Simulation

This approach directly simulates the process described in the problem statement. It iteratively replaces all occurrences of "01" with "10" until no more replacements are possible. The number of iterations represents the time needed.

Time Complexity: O(n*m), where n is the length of the string and m is the number of seconds. In the worst case, m could be close to n (e.g., "010101..."). Each replacement operation takes O(n) time in the worst case due to string replacement operations.

Space Complexity: O(n) in the worst case to store the modified string in each iteration (though some languages might optimize in-place replacement).

Code (Python):

class Solution:
    def secondsToRemoveOccurrences(self, s: str) -> int:
        ans = 0
        while s.count('01'): #efficient check for existance of "01"
            s = s.replace('01', '10') 
            ans += 1
        return ans
 

Code (Java):

class Solution {
    public int secondsToRemoveOccurrences(String s) {
        char[] cs = s.toCharArray(); //Convert to char array for efficient manipulation
        boolean find = true;
        int ans = 0;
        while (find) {
            find = false;
            for (int i = 0; i < cs.length - 1; ++i) {
                if (cs[i] == '0' && cs[i + 1] == '1') {
                    char t = cs[i];
                    cs[i] = cs[i + 1];
                    cs[i + 1] = t;
                    ++i;
                    find = true;
                }
            }
            if (find) {
                ++ans;
            }
        }
        return ans;
    }
}

Other Languages (C++, Go): Similar approaches are used in C++ and Go, leveraging in-place array or byte slice manipulation for potential performance benefits over repeated string creation.

Approach 2: Optimized Approach (Linear Time)

This approach cleverly observes that the number of seconds needed is determined by the maximum number of consecutive zeros before a one. We can achieve a linear time solution by iterating through the string once.

Time Complexity: O(n), where n is the length of the string. We iterate through the string only once.

Space Complexity: O(1), as we use only constant extra space.

Code (Python):

class Solution:
    def secondsToRemoveOccurrences(self, s: str) -> int:
        ans = cnt = 0
        for c in s:
            if c == '0':
                cnt += 1
            elif cnt:
                ans = max(ans + 1, cnt)
        return ans

Code (Java):

class Solution {
    public int secondsToRemoveOccurrences(String s) {
        int ans = 0, cnt = 0;
        for (char c : s.toCharArray()) {
            if (c == '0') {
                ++cnt;
            } else if (cnt > 0) {
                ans = Math.max(ans + 1, cnt);
            }
        }
        return ans;
    }
}

Other Languages (C++, Go): Similar linear-time solutions are implemented in C++ and Go, reflecting the same core logic.

The optimized approach (Approach 2) is significantly more efficient, providing a linear time solution compared to the potentially quadratic time complexity of the simulation approach. Therefore, Approach 2 is the preferred solution for this problem.