C++ 1047.cpp
class Solution {
public:
string removeDuplicates(string s) {
if (s.size() <= 1)
return s;
list<char> seq(s.begin(), s.end());
auto i = seq.begin();
while (next(i) != seq.end())
{
if (*i == *next(i))
{
i = seq.erase(i, next(next(i)));
if (i != seq.begin())
i--;
}
else
i++;
}
return { seq.begin(), seq.end() };
}
};
Difficulty
and has an acceptance rate of about 73% (1+ million submissions).
Typical patterns to solve this problem:
- Stack
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The implementation provides a method to eliminate all adjacent duplicate characters from a mutable string. It first handles trivial inputs, then transforms the string into a doubly-linked list to enable constant-time removal of contiguous segments. A single forward scan drives the core logic, adjusting the iterator when a removal creates a new adjacency that must be re-examined. The final list is converted back into a standard string and returned.
Key Steps
Early return for short inputs
The function begins by checking the length of the input. When the string contains zero or one character, no adjacent pair can exist, so the original string is returned immediately.
if (s.size() <= 1)
return s;
Conversion to a mutable sequence
To support efficient in-place deletions, the characters are copied into a std::list<char>. The list constructor that accepts a pair of iterators builds the list directly from the string’s characters.
list<char> seq(s.begin(), s.end());
Iterative scan with duplicate detection
An iterator i is positioned at the beginning of the list. The loop continues while a successor element exists, guaranteeing that *i and *next(i) are always valid for comparison.
auto i = seq.begin();
while (next(i) != seq.end())
{
// body
}
Inside the loop, the current character is compared with its immediate neighbor. If they match, a removal operation is triggered; otherwise, the iterator simply advances.
if (*i == *next(i))
{
// removal
}
else
i++;
Constant-time removal of a duplicate pair
When a duplicate pair is found, the erase method removes the range that starts at i and ends just after the second duplicate (next(next(i))). Because std::list::erase works in constant time for node removal, the operation does not depend on the size of the list.
i = seq.erase(i, next(next(i)));
Re-examining the new adjacency
After erasing a pair, the iterator may now point to a character that has a new left neighbor. To ensure this new adjacency is checked, the code moves the iterator one step backward unless it is already at the beginning of the list.
if (i != seq.begin())
i--;
Reconstruction of the result string
When the scan finishes, the remaining characters in the list represent the deduplicated sequence. A new std::string is constructed directly from the list’s iterators, avoiding an intermediate copy of individual characters.
return { seq.begin(), seq.end() };
Edge Cases Handled
The algorithm gracefully processes an empty string, returning it unchanged because the early length check captures the zero-size case. A single-character string also bypasses the main loop, preserving the character. When the entire input consists of the same character repeated, each iteration removes a pair until the list becomes empty, and the final conversion yields an empty string.
If duplicate pairs appear at the very start of the string, the iterator begins at the first element, detects the match, erases the pair, and then backs up only if possible, correctly handling the new start of the list. Similarly, duplicates at the end are removed because the loop condition ensures that a successor exists before comparison; after erasing the final pair, the iterator may become equal to seq.end(), causing the loop to terminate.
A more subtle scenario occurs when removal of a pair creates a new adjacent duplicate that was not originally contiguous (for example, the input "abccba"). After the first pair "cc" is erased, the characters 'b' and 'b' become neighbors. The backward step of the iterator positions it on the first 'b', allowing the next loop iteration to detect and remove this newly formed pair. This cascading effect continues until no adjacent duplicates remain.
Performance Optimizations
The choice of std::list<char> is central to the method’s efficiency. By storing each character in a node, the algorithm can excise any contiguous segment with a single pointer update, avoiding the linear-time shifting that would be required in a std::vector or raw string.
The loop maintains a single iterator that moves forward only when no deletion occurs. When a deletion does happen, the iterator is repositioned to the element preceding the removed range (if one exists) rather than restarting from the beginning. This local backtrack eliminates the need for a full restart, ensuring that each character is examined at most a constant number of times.
The final construction of the result string uses the range constructor, which copies the remaining characters in one pass. No intermediate buffers or repeated concatenations are introduced, keeping the overall work proportional to the number of characters that survive the deduplication process.
Together, these design choices produce a solution that processes the input with a single forward traversal, performs deletions in constant time, and rebuilds the output efficiently.
ELI5 - Simplified Explanation
Imagine you have a long train made of colored blocks, where each letter in the string is like a block in a row. The code is a little helper that looks at the train to find any two identical blocks sitting right next to each other. When it spots a pair of siblings touching, it takes both of those blocks away and pulls the rest of the train back together so there are no gaps. After it finishes removing a pair, it moves back slightly to check if the new neighbors that just met are also the same color. It keeps doing this dance down the whole line, sliding back and forth until every block in the row is different from its neighbor. Once the train is tidied up so no two matching blocks are touching, it is ready to be shown as a final result.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Java | |||||||||
| leetcode.ca | C++ | Python | Java | JS | Go | C | Rust | ||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | C++ | ||||||||||
| Garvit244 | Python | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Java | ||||||||||
| leetcode.ca | C, C++, Go, Java, JavaScript, Python, Rust | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | C++ | ||||||||||
| Garvit244 | Python | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 2390: Removing Stars From a String
- problem 2696: Minimum String Length After Removing Substrings
- problem 2716: Minimize String Length
Solved On The Same Day
- problem 125: Valid Palindrome
- problem 191: Number of 1 Bits
- problem 202: Happy Number
- problem 217: Contains Duplicate
- problem 219: Contains Duplicate II
- problem 290: Word Pattern
- problem 383: Ransom Note
- problem 392: Is Subsequence
- problem 1089: Duplicate Zeros
- problem 151: Reverse Words in a String
- problem 187: Repeated DNA Sequences
- problem 51: N-Queens
- problem 52: N-Queens II
- problem 60: Permutation Sequence
- problem 68: Text Justification
- problem 76: Minimum Window Substring
- problem 135: Candy
- problem 140: Word Break II
- problem 220: Contains Duplicate III
- problem 239: Sliding Window Maximum
- problem 352: Data Stream as Disjoint Intervals
- problem 502: IPO
- problem 895: Maximum Frequency Stack
- problem 982: Triples with Bitwise AND Equal To Zero
- problem 995: Minimum Number of K Consecutive Bit Flips
- problem 996: Number of Squareful Arrays
- problem 2136: Earliest Possible Day of Full Bloom
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality