Skip to Content
LeetCode The Hard Way
3500 - 3599

3561 - Resulting String After Adjacent Removals (Medium)

https://leetcode.com/problems/resulting-string-after-adjacent-removals

Problem Statement

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 consecutivecharacters:

  • 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".

Constraints:

  • 1 <= s.length <= 1e5
  • s consists only of lowercase English letters.

Approach 1: Stack

We use a list called resres as a stack and process the string from left to right. For each character, check whether it forms a consecutive pair with the last character in resres. The difference between their ord()ord() values must be 11, or 2525 for the circular pair aa and zz. If they form a pair, remove the last character from resres and skip the current one. Otherwise, add the current character to the stack. After processing the entire string, the characters left in the stack form the result.

For example, in adcbadcb, adding aa and dd gives adad. The next character, cc, removes dd, and then bb removes aa, leaving an empty stack.

The time complexity is O(n)O(n) and the space complexity is O(n)O(n).

Written by@wkw
class Solution:
    def resultingString(self, s: str) -> str:
        res = []
        for c in s:
            if res and abs(ord(res[-1]) - ord(c)) in (1, 25): 
                res.pop()
            else: 
                res.append(c)
        return ''.join(res)

On this page