Time Needed to Rearrange a Binary String
Time Needed to Rearrange a Binary String is a medium dynamic programming problem solved with the 1d dp pattern.
The best approach, optimal (one pass, finishing time of each 1), runs in O(n) time and O(1) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from simulate every second up.
Problem
You are given a binary string s, made only of the characters '0' and '1'.
Every second, all places where a '0' is immediately followed by a '1' are found at once, and each such pair "01" is replaced by "10" at the same moment. Pairs never overlap, because a '1' that moves left can never also be the '0' of another pair.
This repeats until the string no longer contains "01" anywhere. Return the number of seconds the process takes. If s contains no "01" from the start, the answer is 0.
Examples
Example 1
- Input
s = "001011"- Output
4- Why
- Second 1 turns it into "010101", second 2 into "101010", second 3 into "110100" and second 4 into "111000". Now every 1 is ahead of every 0, so no "01" is left after 4 seconds.
Example 2
- Input
s = "1110100"- Output
1- Why
- There is a single "01", at positions 3 and 4. One second swaps it and gives "1111000", which has no "01".
Example 3
- Input
s = "1100"- Output
0- Why
- The string never has a 0 directly before a 1, so nothing changes and the answer is 0.
Constraints
1 <= s.length <= 1000- Every character of
sis either'0'or'1'.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 14 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Simulate every second | O(n²) | O(n) |
| Optimal (one pass, finishing time of each 1) | O(n) | O(1) |
1Simulate every second
O(n²)Each round is a pass over n characters, and the answer, which is the number of rounds, is at most n.O(n)A mutable copy of the string.Do exactly what the statement says. In each round, scan the string from left to right. Whenever a 0 is directly followed by a 1, swap them and jump past both, so a character never moves twice in one round. Count the rounds until a scan finds nothing to swap.
- Copy s into a char array and set seconds = 0.
- Repeat: scan i from 0; if chars[i] is 0 and chars[i + 1] is 1, swap them and skip to i + 2, otherwise go to i + 1.
- If the scan swapped nothing, stop; otherwise add one to seconds and scan again.
- Return seconds.
class Solution {
public int secondsToRemoveOccurrences(String s) {
char[] chars = s.toCharArray();
int seconds = 0;
boolean changed = true;
while (changed) {
changed = false;
for (int i = 0; i + 1 < chars.length; i++) {
if (chars[i] == '0' && chars[i + 1] == '1') {
chars[i] = '1';
chars[i + 1] = '0';
i++;
changed = true;
}
}
if (changed) seconds++;
}
return seconds;
}
}class Solution:
def secondsToRemoveOccurrences(self, s: str) -> int:
chars = list(s)
seconds = 0
changed = True
while changed:
changed = False
i = 0
while i + 1 < len(chars):
if chars[i] == '0' and chars[i + 1] == '1':
chars[i] = '1'
chars[i + 1] = '0'
i += 1
changed = True
i += 1
if changed:
seconds += 1
return secondsclass Solution {
public:
int secondsToRemoveOccurrences(string s) {
string chars = s;
int seconds = 0;
bool changed = true;
while (changed) {
changed = false;
for (int i = 0; i + 1 < (int)chars.size(); i++) {
if (chars[i] == '0' && chars[i + 1] == '1') {
chars[i] = '1';
chars[i + 1] = '0';
i++;
changed = true;
}
}
if (changed) seconds++;
}
return seconds;
}
};function secondsToRemoveOccurrences(s) {
const chars = s.split("");
let seconds = 0;
let changed = true;
while (changed) {
changed = false;
for (let i = 0; i + 1 < chars.length; i++) {
if (chars[i] === '0' && chars[i + 1] === '1') {
chars[i] = '1';
chars[i + 1] = '0';
i++;
changed = true;
}
}
if (changed) seconds++;
}
return seconds;
}2Optimal (one pass, finishing time of each 1)
O(n)One pass over the string with constant work per character.O(1)Only two counters.The ones keep their relative order, and the last one to settle decides the answer. Walk left to right, counting the zeros seen so far. A 1 with no zero before it is already home. A 1 with zeros zeros before it must jump over all of them, so it needs at least zeros seconds. It also cannot finish before the previous moving 1 has finished plus one more second, because it can only step into a spot that the previous 1 has just left. So its finishing time is max(seconds + 1, zeros), where seconds is the finishing time of the previous moving 1. The value after the last 1 is the answer.
- zeros = 0, seconds = 0.
- For each character c of s: if c is 0, add one to zeros.
- Otherwise, if zeros > 0, set seconds = max(seconds + 1, zeros).
- Return seconds.
class Solution {
public int secondsToRemoveOccurrences(String s) {
int zeros = 0, seconds = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '0') {
zeros++;
} else if (zeros > 0) {
seconds = Math.max(seconds + 1, zeros);
}
}
return seconds;
}
}class Solution:
def secondsToRemoveOccurrences(self, s: str) -> int:
zeros = 0
seconds = 0
for c in s:
if c == '0':
zeros += 1
elif zeros > 0:
seconds = max(seconds + 1, zeros)
return secondsclass Solution {
public:
int secondsToRemoveOccurrences(string s) {
int zeros = 0, seconds = 0;
for (char c : s) {
if (c == '0') {
zeros++;
} else if (zeros > 0) {
seconds = max(seconds + 1, zeros);
}
}
return seconds;
}
};function secondsToRemoveOccurrences(s) {
let zeros = 0, seconds = 0;
for (let i = 0; i < s.length; i++) {
if (s[i] === '0') {
zeros++;
} else if (zeros > 0) {
seconds = Math.max(seconds + 1, zeros);
}
}
return seconds;
}Edge cases to test
- No "01" at all, such as all ones, all zeros, or ones already before zeros (answer 0)
- A single character
- Leading ones, which are already in place and never move
- A run of ones after many zeros: the ones block each other, so each extra one waits one more second
- Zeros that come after the last 1, which never matter
Hints
Hint 1
Each second, every 1 that has a 0 right before it moves one step to the left. The process ends when all 1s are at the front.
Hint 2
The string has at most 1000 characters, and the answer is never more than its length. Simulating second by second is fast enough.
Hint 3
Look at one 1 at a time, from left to right. It must jump over every 0 before it, and it can never overtake the 1 just before it. How does its finishing time relate to the previous 1's finishing time?
Hint 4
If z zeros come before a 1, that 1 needs at least z seconds, and at least one second more than the previous moving 1. Its finishing time is the larger of the two.
FAQ
What is the best time complexity for Time Needed to Rearrange a Binary String?
Optimal (one pass, finishing time of each 1) runs in O(n) time and O(1) extra space. One pass over the string with constant work per character.
Which pattern does Time Needed to Rearrange a Binary String use?
It is a dynamic programming problem that uses the 1d dp pattern. Other problems with the same pattern: Fibonacci Number, Climbing Stairs, Min Cost Climbing Stairs (2 jumps).
Is there a brute force solution for Time Needed to Rearrange a Binary String?
Yes. Simulate every second takes O(n²) time and O(n) space. Do exactly what the statement says.
Which edge cases should I test for Time Needed to Rearrange a Binary String?
No "01" at all, such as all ones, all zeros, or ones already before zeros (answer 0); A single character; Leading ones, which are already in place and never move; A run of ones after many zeros: the ones block each other, so each extra one waits one more second; Zeros that come after the last 1, which never matter.