Skip to content

Instantly share code, notes, and snippets.

@doyedele1
Last active March 14, 2022 09:00
Show Gist options
  • Save doyedele1/178ac9f71876cd4e58b8132e06c1e251 to your computer and use it in GitHub Desktop.
Save doyedele1/178ac9f71876cd4e58b8132e06c1e251 to your computer and use it in GitHub Desktop.
Remove All Adjacent Duplicates in String II
'''
Explanation:
- deeedbbcccbdaa
[[d,1], [e,3]]
[[d,2]]
TC - O(2n) = O(n) where n is the size of the input string
SC - O(n)
'''
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
# create a stack with [character, count]
stack = []
for char in s:
if stack and stack[-1][0] == char:
stack[-1][1] += 1
else:
stack.append([char, 1])
if stack and stack[-1][1] == k:
stack.pop()
# char * num prints the char in num times
return "".join([char * num for char, num in stack])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment