09 Sept 2026Go / Python / TypeScriptEasy

Remove All Adjacent Duplicates in String

Repeatedly remove equal adjacent character pairs until none remain.

Use the output as a stack: pop when the next character matches the top, otherwise push it.

complexity

O(n) time and O(n) space.

solution files

  • Go remove-all-adjacent-duplicates-in-string/solution.go
  • Python remove-all-adjacent-duplicates-in-string/solution.py
  • TypeScript remove-all-adjacent-duplicates-in-string/solution.ts

Solution files

Goremove-all-adjacent-duplicates-in-string/solution.go
package main

func removeDuplicates(s string) string {
	stack := []byte{}
	for index := range s {
		if len(stack) > 0 && stack[len(stack)-1] == s[index] {
			stack = stack[:len(stack)-1]
		} else {
			stack = append(stack, s[index])
		}
	}
	return string(stack)
}
Pythonremove-all-adjacent-duplicates-in-string/solution.py
class Solution:
    def removeDuplicates(self, s: str) -> str:
        stack: list[str] = []
        for character in s:
            if stack and stack[-class="syntax-number">1] == character: stack.pop()
            else: stack.append(character)
        return class="syntax-string">"".join(stack)
TypeScriptremove-all-adjacent-duplicates-in-string/solution.ts
function removeDuplicates(s: string): string {
  const stack: string[] = [];
  for (const character of s) { if (stack[stack.length - class="syntax-number">1] === character) stack.pop(); else stack.push(character); }
  return stack.join(class="syntax-string">"");
}