Skip to main content
Back to problems
#3561
Medium Algorithms

Resulting string after adjacent removals

String Stack Simulation
56.6% acceptance
Feb 25, 2026
89
3
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.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn resulting_string(s: String) -> String {
    // Stack-based: push char, check if top two are consecutive (|a-b|==1 or {a,b}=={a,z}).
    // Remove leftmost pair -> we process left to right, remove when top of stack matches.
    let mut stack: Vec<u8> = Vec::new();
    for b in s.bytes() {
      if let Some(&top) = stack.last() {
        let diff = (top as i32 - b as i32).unsigned_abs();
        if diff == 1 || diff == 25 {
          stack.pop();
          continue;
        }
      }
      stack.push(b);
    }
    String::from_utf8(stack).unwrap()
  }
}