Intuition
Scan left to right and keep a stack of surviving characters; a new character that is alphabet-adjacent to the stack's top cancels it instead of being kept.
Explanation
Why a stack?
The operation always removes the leftmost adjacent pair, then shifts everything left and looks again from the start. Doing that literally is slow, but notice what it means: once a character survives, the only thing that can ever remove it is the very next surviving character to its right. That is exactly the "most recent unmatched item" question a stack answers.
So scan the string once, keeping a stack of characters that have survived so far:
- Read the next character
c. - If the stack is non-empty and its top is consecutive in the alphabet with
c(treating the alphabet as circular, so'a'and'z'count), thencand the top cancel each other — pop the top and dropc. - Otherwise
chas nothing to pair with yet — push it. - At the end, the stack read bottom-to-top is the answer.
Two letters are consecutive when |ord(a) - ord(b)| is 1, or 25 for the circular 'a'/'z' wrap.
Worked example: s = "adcb"
'a': stack empty, push. Stack:a'd': top is'a', gap is 3 — not adjacent. Push. Stack:a d'c': top is'd', gap is 1 — adjacent! Pop'd', drop'c'. Stack:a'b': top is'a', gap is 1 — adjacent! Pop'a', drop'b'. Stack: (empty)
The stack is empty, so the answer is "" — matching the rule's cascade where removing "dc" leaves "ab", which then removes to "".
Complexity
- Time: O(n) — each character is pushed and popped at most once.
- Space: O(n) — the stack in the worst case (no cancellations) holds every character.
Implementation
class Solution {
public String resultingString(String s) {
StringBuilder stack = new StringBuilder();
for (int k = 0; k < s.length(); k++) {
char ch = s.charAt(k);
int len = stack.length();
if (len > 0 && consecutive(stack.charAt(len - 1), ch)) {
stack.deleteCharAt(len - 1);
} else {
stack.append(ch);
}
}
return stack.toString();
}
private boolean consecutive(char a, char b) {
int d = Math.abs(a - b);
return d == 1 || d == 25;
}
}