2380. Time Needed to Rearrange a Binary String LeetCode Solution
In this guide, you will get 2380. Time Needed to Rearrange a Binary String LeetCode Solution with the best time and space complexity. The solution to Time Needed to Rearrange a Binary String problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Time Needed to Rearrange a Binary String solution in C++
- Time Needed to Rearrange a Binary String solution in Java
- Time Needed to Rearrange a Binary String solution in Python
- Additional Resources

Problem Statement of 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?
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
2380. Time Needed to Rearrange a Binary String LeetCode Solution in C++
class Solution {
public:
int secondsToRemoveOccurrences(string s) {
int ans = 0;
int zeros = 0;
for (const char c : s)
if (c == '0')
++zeros;
else if (zeros > 0) // c == '1'
ans = max(ans + 1, zeros);
return ans;
}
};
/* code provided by PROGIEZ */
2380. Time Needed to Rearrange a Binary String LeetCode Solution in Java
class Solution {
public int secondsToRemoveOccurrences(String s) {
int ans = 0;
int zeros = 0;
for (final char c : s.toCharArray())
if (c == '0')
++zeros;
else if (zeros > 0) // c == '1'
ans = Math.max(ans + 1, zeros);
return ans;
}
}
// code provided by PROGIEZ
2380. Time Needed to Rearrange a Binary String LeetCode Solution in Python
class Solution:
def secondsToRemoveOccurrences(self, s: str) -> int:
ans = 0
zeros = 0
for c in s:
if c == '0':
zeros += 1
elif zeros > 0: # c == '1'
ans = max(ans + 1, zeros)
return ans
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.