#3561

Resulting String After Adjacent Removals

Medium
StringStackSimulationStackGreedy
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)

Use a stack to efficiently manage removals. Push characters onto the stack and check the top for adjacent pairs, allowing for quick removals.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an empty stack.
  2. 2Step 2: Traverse each character in the string; push it onto the stack if it doesn't form an adjacent pair with the top of the stack.
  3. 3Step 3: If it does form a pair, pop the stack (remove the top character).
solution.py8 lines
1def removeAdjacent(s):
2    stack = []
3    for char in s:
4        if stack and (abs(ord(stack[-1]) - ord(char)) == 1 or (stack[-1], char) in [('a', 'z'), ('z', 'a')]):
5            stack.pop()
6        else:
7            stack.append(char)
8    return ''.join(stack)

Complexity note: The stack allows for efficient management of removals, processing each character in a single pass.

  • 1Adjacent pairs can be removed in constant time with a stack.
  • 2Using a stack helps manage the order of characters efficiently.

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