Lexicographically Smallest String After Adjacent Removals - Problem
Find the lexicographically smallest string after optimally removing consecutive character pairs from a string of lowercase letters.
You're given a string
• Remove any pair of adjacent characters that are consecutive in the alphabet (like 'a' and 'b', or 'b' and 'a')
• The alphabet is circular, so 'a' and 'z' are also consecutive
• After removal, remaining characters shift left to fill the gap
Your goal is to find the lexicographically smallest string possible after performing these operations optimally.
Example: "abdc" → remove "ab" → "dc" → remove "cd" → "" (empty string)
You're given a string
s containing only lowercase English letters. You can perform the following operation any number of times:• Remove any pair of adjacent characters that are consecutive in the alphabet (like 'a' and 'b', or 'b' and 'a')
• The alphabet is circular, so 'a' and 'z' are also consecutive
• After removal, remaining characters shift left to fill the gap
Your goal is to find the lexicographically smallest string possible after performing these operations optimally.
Example: "abdc" → remove "ab" → "dc" → remove "cd" → "" (empty string)
Input & Output
example_1.py — Basic Elimination
$
Input:
s = "abdc"
›
Output:
""
💡 Note:
Remove 'ab' → 'dc', then remove 'cd' → empty string. This is lexicographically smallest.
example_2.py — Circular Consecutive
$
Input:
s = "zabc"
›
Output:
"bc"
💡 Note:
Remove 'za' (circular consecutive) → 'bc'. No more consecutive pairs can be removed.
example_3.py — No Removals
$
Input:
s = "aceg"
›
Output:
"aceg"
💡 Note:
No adjacent characters are consecutive, so no pairs can be removed. Original string is returned.
Constraints
- 1 ≤ s.length ≤ 105
- s consists of lowercase English letters only
- The alphabet is circular: 'a' and 'z' are consecutive
Visualization
Tap to expand
Understanding the Visualization
1
Initialize
Start with empty stack and process string left-to-right
2
Check Top
For each character, check if it forms consecutive pair with stack top
3
Eliminate or Add
If consecutive, pop the pair. Otherwise, push the character
4
Continue
Repeat until all characters processed
Key Takeaway
🎯 Key Insight: The stack-based approach automatically finds the optimal solution by processing characters left-to-right and immediately eliminating consecutive pairs, ensuring the lexicographically smallest result without trying all possibilities.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code