Resulting String After Adjacent Removals Problem
Description
LeetCode Problem 3561.
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".
Constraints:
1 <= s.length <= 10^5sconsists only of lowercase English letters.
Solution
Approach: Stack
Process the characters from left to right with a stack. If the current character is consecutive with the one on top of the stack (their codes differ by 1, or by 25 for the wrap-around between a and z), pop the top; otherwise push the current character. Whatever remains in the stack, read from bottom to top, is the final string.
Complexity: time O(n), space O(n), where n is the length of the string.
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)