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 'dc' → 'ba', then remove 'ba' → 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
Resulting String After Adjacent Removals INPUT String s = "cabd" c idx 0 a idx 1 b idx 2 d idx 3 Circular Alphabet: a b c d ... y z a 'a'-'b' and 'z'-'a' are consecutive pairs ALGORITHM STEPS 1 Use Stack Process chars left to right 2 Check Consecutive |char - top| == 1 or 25 3 Pop or Push Remove pair or add char 4 Build Result Stack contents = answer Trace: char stack action 'c' [c] push 'a' [c,a] push 'b' [c] pop a-b 'd' [c,d] push FINAL RESULT After all operations: c d Output: "cd" [OK] No more pairs! Removed pairs: 'a' + 'b' removed 'c' and 'd' are NOT consecutive (differ by 1) Key Insight: Stack-based approach simulates removal operations in O(n) time. For each character, check if it forms a consecutive pair with stack top. If yes, pop (remove pair); otherwise push. Handle circular case: 'a' and 'z' differ by 25 in ASCII. TutorialsPoint - Resulting String After Adjacent Removals | Optimal Stack Solution
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