#1209

Remove All Adjacent Duplicates in String II

Medium
StringStackStackTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using a stack allows us to efficiently manage the characters and their counts. We can push characters onto the stack and keep track of their counts, removing them when they reach k.

⚙️

Algorithm

6 steps
  1. 1Step 1: Initialize an empty stack to hold pairs of characters and their counts.
  2. 2Step 2: Iterate through each character in the string.
  3. 3Step 3: If the stack is not empty and the top character matches the current character, increment the count.
  4. 4Step 4: If the count reaches k, pop the character from the stack.
  5. 5Step 5: If the character is new, push it onto the stack with a count of 1.
  6. 6Step 6: Construct the final string from the stack.
solution.py10 lines
1def removeDuplicates(s, k):
2    stack = []
3    for char in s:
4        if stack and stack[-1][0] == char:
5            stack[-1][1] += 1
6            if stack[-1][1] == k:
7                stack.pop()
8        else:
9            stack.append([char, 1])
10    return ''.join(char * count for char, count in stack)

Complexity note: The time complexity is O(n) because we traverse the string once, and the space complexity is O(n) due to the stack storing characters and their counts.

  • 1Using a stack helps manage counts of characters efficiently.
  • 2Adjacent duplicates can be removed in a single pass with a stack.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.