#3563
Lexicographically Smallest String After Adjacent Removals
HardStringDynamic ProgrammingStackGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using a stack-like approach allows us to efficiently manage removals and build the smallest string without generating all combinations.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an empty stack to build the result string.
- 2Step 2: Iterate through each character in the string. If the current character and the top of the stack are consecutive, pop the stack.
- 3Step 3: Push the current character onto the stack. Finally, join the stack to form the result.
solution.py8 lines
1def lexicographically_smallest(s):
2 stack = []
3 for char in s:
4 while stack and (abs(ord(stack[-1]) - ord(char)) == 1 or (stack[-1] == 'a' and char == 'z') or (stack[-1] == 'z' and char == 'a')):
5 stack.pop()
6 stack.append(char)
7 return ''.join(stack)
8ℹ
Complexity note: The stack efficiently manages removals, allowing us to process each character in linear time.
- 1Adjacent characters can be removed if they are consecutive in the alphabet.
- 2Using a stack helps efficiently manage removals.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.