Recursively remove all adjacent duplicates
Pattern: String building
Each pass removes every run of two or more equal neighbours. Removing runs can bring new equal characters together, so repeat the pass until one pass removes nothing.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Given a string, remove every character that has an equal neighbour, so every run of two or more equal characters goes
completely. Repeat this on the result until no two neighbours are equal. Return the final string. For example,
"azxxzy" gives "ay", "geeksforgeeg" gives "gksfor", and "caaabbbaac" gives "".
This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name
removeDuplicates and this exact rule (each pass removes whole runs, then repeat) are this guide's own. LeetCode's
Remove All Adjacent Duplicates In String removes pairs instead, which gives different answers.
Think first
- In
"caaabbbaac", what does one pass remove? What is left? - Why is one pass not enough?
- How do you know you are finished?
Hints
Brute force, and why it fails
Repeated passes, as described, cost O(n) each, and each pass that changes something removes at least 2 characters. So
there are at most n / 2 passes: O(n²) in the worst case. A cleverer stack-based method can do it in O(n), but its
details are easy to get wrong, and the simple loop is fast for short strings.
The key insight
The rule is applied to the whole string at once and then again. "Until nothing changes" is a loop whose stop test is "this pass made no change".
Dry run
s = azxxzy. Find runs of equal neighbours. Only xx has length 2 or more.
The plan
loop:
next = empty builder, i = 0
while i < n:
j = i
while j < n and s[j] == s[i]: j = j + 1
if j - i == 1: append s[i] to next
i = j
if len(next) == len(s): return s
s = next
Complexity
- Time
O(n²) worst- Space
O(n)
Each pass is O(n). Every pass that changes the string makes it at least 2 shorter.
Edge cases
- No equal neighbours, as in
"abc": unchanged. - All equal, as in
"aaaa":"". - Runs that join after a removal, as in
"gghhg": firstggandhhgo, leaving"g".
I've built my logic, show the code
Java
class Solution {
public String removeDuplicates(String s) {
while (true) {
StringBuilder next = new StringBuilder();
int i = 0;
while (i < s.length()) {
int j = i;
while (j < s.length() && s.charAt(j) == s.charAt(i)) j++; // s[i..j-1] is one run
if (j - i == 1) next.append(s.charAt(i)); // keep only runs of length 1
i = j;
}
if (next.length() == s.length()) return s; // nothing removed: done
s = next.toString(); // repeat on the shorter string
}
}
}C++
class Solution {
public:
string removeDuplicates(string s) {
while (true) {
string next;
size_t i = 0;
while (i < s.size()) {
size_t j = i;
while (j < s.size() && s[j] == s[i]) j++; // s[i..j-1] is one run
if (j - i == 1) next += s[i]; // keep only runs of length 1
i = j;
}
if (next.size() == s.size()) return s; // nothing removed: done
s = next; // repeat on the shorter string
}
}
};Python
class Solution:
def removeDuplicates(self, s: str) -> str:
while True:
out, i = [], 0
while i < len(s):
j = i
while j < len(s) and s[j] == s[i]:
j += 1 # s[i..j-1] is one run
if j - i == 1:
out.append(s[i]) # keep only runs of length 1
i = j
nxt = "".join(out)
if len(nxt) == len(s):
return s # nothing removed: done
s = nxt # repeat on the shorter stringCommon mistakes
- Removing pairs (two at a time), which leaves one character of an odd run.
- Doing a single pass.
- Changing the string while still scanning it in the same pass.