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 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
Stack-Based Elimination VisualizationInput String: "abdc"abdcStack Evolution:Step 1: Process 'a'aStack: [a]Step 2: Process 'b'Consecutive with 'a' → Remove bothStack: []Step 3: Process 'd'dStack: [d]Step 4: Process 'c'Consecutive with 'd' → Remove bothStack: []Algorithm Explanation:1. Process characters left-to-right using a stack2. If current character forms consecutive pair with stack top → eliminate both3. Otherwise, push current character to stack4. Consecutive means |char1 - char2| = 1 or |char1 - char2| = 25 (circular: z-a)Final Result: Empty string "" (lexicographically smallest possible)OPTIMALO(n) timeO(n) space
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.
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
31.3K Views
Medium-High Frequency
~25 min Avg. Time
1.3K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen