What is Remove Adjacent Duplicates
Repeatedly delete two adjacent letters that are the same. Return the letters that remain, left to right.
Approach
Visualization & algorithm
The finished picture is on screen when the page opens. Next and Play start from the first step. The controls sit under the picture and the pseudocode.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each letter is pushed and popped at most once. |
| Space | O(n) | A string with no pairs keeps every letter. |
Implementation
def solve(self, s):
st = []
for ch in s:
if st and st[-1] == ch:
st.pop()
else:
st.append(ch)
return ''.join(st)