Problem 1047

Abstract / Summary

Remove consecutive repeating letters from a string repeatedly until no more duplicates are adjacent.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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() };
    }
};
24 lines | 534 bytes | submitted August 9, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 73% (1+ million submissions).

Typical patterns to solve this problem:
  • Stack
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.89 | σ = 1.66

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
38 links | 24 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

9 easy 2 medium 16 hard
28 solutions   August 9, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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