Time Needed to Rearrange a Binary String LeetCode Solution

Problem – 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'.

Time Needed to Rearrange a Binary String LeetCode Solution in Java

public int secondsToRemoveOccurrences(String s) {
    int zeros = 0, seconds = 0;
    for (int i = 0; i < s.length(); ++i) {
        zeros += s.charAt(i) == '0' ? 1 : 0;
        if (s.charAt(i) == '1' && zeros > 0)
            seconds = Math.max(seconds + 1, zeros);
    }
    return seconds;        
}

Time Needed to Rearrange a Binary String LeetCode Solution in C++

int secondsToRemoveOccurrences(string s) {
    int zeros = 0, seconds = 0;
    for (int i = 0; i < s.size(); ++i) {
        zeros += s[i] == '0';
        if (s[i] == '1' && zeros)
            seconds = max(seconds + 1, zeros);
    }
    return seconds;
}

Time Needed to Rearrange a Binary String LeetCode Solution in Python

class Solution:
    def secondsToRemoveOccurrences(self, s: str) -> int:
        cnt = 0
        while ('01' in s):
            s = s.replace('01', '10')
            cnt += 1
        return cnt
Time Needed to Rearrange a Binary String LeetCode Solution Review:

In our experience, we suggest you solve this Time Needed to Rearrange a Binary String LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Time Needed to Rearrange a Binary String LeetCode Solution

Find on LeetCode

Conclusion:

I hope this Time Needed to Rearrange a Binary String LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published.