Lexicographically Smallest String After Adjacent Removals - Problem

You are given a string s consisting of lowercase English letters. You can perform the following operation any number of times (including zero):

Remove any pair of adjacent characters in the string that are consecutive in the alphabet, in either order (e.g., 'a' and 'b', or 'b' and 'a'). Shift the remaining characters to the left to fill the gap.

Return the lexicographically smallest string that can be obtained after performing the operations optimally.

Note: Consider the alphabet as circular, thus 'a' and 'z' are consecutive.

Input & Output

Example 1 — Consecutive Pairs
$ Input: s = "abdc"
Output: ""
💡 Note: Remove 'ab' to get "dc", then remove 'dc' to get empty string. Result is lexicographically smallest.
Example 2 — Circular Case
$ Input: s = "azyx"
Output: "yx"
💡 Note: Remove 'za' (circular consecutive) to get "yx". No more consecutive pairs can be removed.
Example 3 — No Removals
$ Input: s = "aceg"
Output: "aceg"
💡 Note: No adjacent characters are consecutive, so no pairs can be removed.

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists of lowercase English letters

Visualization

Tap to expand
Lexicographically Smallest String After RemovalsInput String "abdc":abdcconsecutiveconsecutiveStack Processing:Remove "ab" → Stack becomes emptyRemove "dc" → Stack remains emptyOutput: "" (empty string)All consecutive pairs removed optimally
Understanding the Visualization
1
Input
String with potential consecutive adjacent pairs
2
Process
Remove consecutive pairs optimally using stack
3
Output
Lexicographically smallest remaining string
Key Takeaway
🎯 Key Insight: Use a stack to greedily remove consecutive pairs as you process the string left to right
Asked in
Google 45 Meta 35 Amazon 30
28.5K Views
Medium Frequency
~25 min Avg. Time
890 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