Skip to content
MediumStacks QueuesAI interview only

Resulting String After Adjacent Removals

Asked atgoogleamazonmicrosoft

01 · Problem

You are given a string s of lowercase English letters. Two letters are called consecutive if they are next to each other in the alphabet, treating the alphabet as circular: 'a'/'b', 'm'/'n' and also 'z'/'a' are consecutive (in either order), while 'a'/'c' or two equal letters are not.

While the string contains two adjacent characters that are consecutive letters, remove the leftmost such pair and close the gap. Return the string that remains when no more removals are possible (possibly the empty string "").

02 · Examples

Example 01
Input
s = "xyzb"
Output
"zb"

The leftmost consecutive pair is "xy"; removing it leaves "zb", and 'z' and 'b' are not consecutive.

Example 02
Input
s = "mlkp"
Output
"kp"

"ml" is consecutive (order does not matter); removing it leaves "kp", which cannot shrink further.

Example 03
Input
s = "zadb"
Output
"db"

"za" is consecutive because the alphabet wraps around; removing it leaves "db", which has no consecutive pair.

03 · Constraints

  • 011 <= s.length <= 105
  • 02s consists only of lowercase English letters
  • 03Adjacency wraps around: 'z' and 'a' are consecutive

04 · Optimal complexity

Time
O(n)
Space
O(n)
05 · Two ways to work on it

Practice it alone or rehearse it as an interview.

Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.