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 Adjacent Removals INPUT String s = "abdc" a b d c idx 0 idx 1 idx 2 idx 3 Circular Alphabet: 'a'-'b', 'b'-'c', 'c'-'d' 'z'-'a' are consecutive Adjacent Consecutive Pairs: 'a','b' 'd','c' Both pairs can be removed! ALGORITHM STEPS 1 Find consecutive pair 'a' and 'b' at idx 0,1 a b d c 2 Remove 'ab' pair String becomes "dc" d c 3 Find next pair 'd' and 'c' consecutive d c 4 Remove 'dc' pair String becomes "" GREEDY FINAL RESULT After all removals: "" Output: "" Empty string is the lexicographically smallest possible! OK "abdc" --> "dc" --> "" Key Insight: Greedy approach: Always remove consecutive adjacent pairs when found. The circular alphabet means 'z' and 'a' are also consecutive. Removing pairs early creates new adjacent pairs, potentially allowing complete string elimination for the lexicographically smallest result. TutorialsPoint - Lexicographically Smallest String After Adjacent Removals | Greedy Approach
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