Resulting String After Adjacent Removals - Problem

You are given a string s consisting of lowercase English letters. You must repeatedly perform the following operation while the string s has at least two consecutive characters:

  • Remove the leftmost 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 resulting string after no more operations can be performed.

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

Input & Output

Example 1 — Basic Removal
$ Input: s = "cabd"
Output: "cd"
💡 Note: First we find the consecutive pair 'a' and 'b' at positions 1,2. After removing them, we get 'cd' with no more consecutive pairs.
Example 2 — Multiple Removals
$ Input: s = "dcba"
Output: ""
💡 Note: Remove 'cb' → 'da', then remove 'da' (circular: 'd' and 'a' are consecutive) → empty string.
Example 3 — Circular Case
$ Input: s = "za"
Output: ""
💡 Note: Since the alphabet is circular, 'z' and 'a' are consecutive, so they form a removable pair.

Constraints

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

Visualization

Tap to expand
Adjacent Character Removal ProcessInput:cabd← consecutive pairAfter Removal:cdNo more consecutive pairs foundFinal Result: "cd"
Understanding the Visualization
1
Input
String with consecutive letter pairs like 'ab', 'zy'
2
Process
Remove leftmost consecutive pairs repeatedly
3
Output
Final string with no consecutive pairs
Key Takeaway
🎯 Key Insight: Use a stack to efficiently track and remove consecutive pairs in a single pass
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
24.9K 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