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.
Example 1:
Input:s = "abc"
Output:"c"
Explanation:
Remove "ab" from the string, leaving "c" as the remaining string.
No further operations are possible. Thus, the resulting string after all possible removals is "c".
Example 2:
Input:s = "adcb"
Output:""
Explanation:
Remove "dc" from the string, leaving "ab" as the remaining string.
Remove "ab" from the string, leaving "" as the remaining string.
No further operations are possible. Thus, the resulting string after all possible removals is "".
Example 3:
Input:s = "zadb"
Output:"db"
Explanation:
Remove "za" from the string, leaving "db" as the remaining string.
No further operations are possible. Thus, the resulting string after all possible removals is "db".
Problem summary: 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.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Stack
Example 1
"abc"
Example 2
"adcb"
Example 3
"zadb"
Step 02
Core Insight
What unlocks the optimal approach
Traverse the string from left to right and use a stack to perform the removals.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3561: Resulting String After Adjacent Removals
class Solution {
public String resultingString(String s) {
StringBuilder stk = new StringBuilder();
for (char c : s.toCharArray()) {
if (stk.length() > 0 && isContiguous(stk.charAt(stk.length() - 1), c)) {
stk.deleteCharAt(stk.length() - 1);
} else {
stk.append(c);
}
}
return stk.toString();
}
private boolean isContiguous(char a, char b) {
int t = Math.abs(a - b);
return t == 1 || t == 25;
}
}
// Accepted solution for LeetCode #3561: Resulting String After Adjacent Removals
func resultingString(s string) string {
isContiguous := func(a, b rune) bool {
x := abs(int(a - b))
return x == 1 || x == 25
}
stk := []rune{}
for _, c := range s {
if len(stk) > 0 && isContiguous(stk[len(stk)-1], c) {
stk = stk[:len(stk)-1]
} else {
stk = append(stk, c)
}
}
return string(stk)
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
# Accepted solution for LeetCode #3561: Resulting String After Adjacent Removals
class Solution:
def resultingString(self, s: str) -> str:
stk = []
for c in s:
if stk and abs(ord(c) - ord(stk[-1])) in (1, 25):
stk.pop()
else:
stk.append(c)
return "".join(stk)
// Accepted solution for LeetCode #3561: Resulting String After Adjacent Removals
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3561: Resulting String After Adjacent Removals
// class Solution {
// public String resultingString(String s) {
// StringBuilder stk = new StringBuilder();
// for (char c : s.toCharArray()) {
// if (stk.length() > 0 && isContiguous(stk.charAt(stk.length() - 1), c)) {
// stk.deleteCharAt(stk.length() - 1);
// } else {
// stk.append(c);
// }
// }
// return stk.toString();
// }
//
// private boolean isContiguous(char a, char b) {
// int t = Math.abs(a - b);
// return t == 1 || t == 25;
// }
// }
// Accepted solution for LeetCode #3561: Resulting String After Adjacent Removals
function resultingString(s: string): string {
const stk: string[] = [];
const isContiguous = (a: string, b: string): boolean => {
const x = Math.abs(a.charCodeAt(0) - b.charCodeAt(0));
return x === 1 || x === 25;
};
for (const c of s) {
if (stk.length && isContiguous(stk.at(-1)!, c)) {
stk.pop();
} else {
stk.push(c);
}
}
return stk.join('');
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n)
Space
O(n)
Approach Breakdown
BRUTE FORCE
O(n²) time
O(1) space
For each element, scan left (or right) to find the next greater/smaller element. The inner scan can visit up to n elements per outer iteration, giving O(n²) total comparisons. No extra space needed beyond loop variables.
MONOTONIC STACK
O(n) time
O(n) space
Each element is pushed onto the stack at most once and popped at most once, giving 2n total operations = O(n). The stack itself holds at most n elements in the worst case. The key insight: amortized O(1) per element despite the inner while-loop.
Shortcut: Each element pushed once + popped once → O(n) amortized. The inner while-loop does not make it O(n²).
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
Breaking monotonic invariant
Wrong move: Pushing without popping stale elements invalidates next-greater/next-smaller logic.
Usually fails on: Indices point to blocked elements and outputs shift.
Fix: Pop while invariant is violated before pushing current element.