Remove All Adjacent Duplicates In String Visualizer & Step-by-Step Algorithm Solution

Repeatedly remove adjacent, duplicate character pairs from a string using a LIFO stack until no duplicates remain.

Category: stack | Difficulty: Easy

Tags: Stack, String, Adjacent Duplicates, Simulation

Remove All Adjacent Duplicates In String

Input Characters (s)
a
0
b
1
b
2
a
3
c
4
a
5
Push / Pop (Top)
(Empty Stack)
Character Stack
100%
state
currentStack(empty)
stackSize0
s"abbaca"
length6
Initialization
1/27
Explanation

Starting removeDuplicates with string "abbaca" (length 6).

Source Code
1function removeDuplicates(s: string): string {
2 const stack: string[] = [];
3 for (let i = 0; i < s.length; i++) {
4 const char = s[i];
5 if (stack.length > 0 && stack[stack.length - 1] === char) {
6 stack.pop();
7 } else {
8 stack.push(char);
9 }
10 }
11 return stack.join('');
12}