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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code