Sponsored
Sponsored
Use a stack data structure to efficiently remove adjacent duplicates. Traverse through the string, and for each character, check the top of the stack. If the top of the stack is equal to the current character, pop the stack. Otherwise, push the current character onto the stack. Finally, reconstruct the string from the stack.
Time Complexity: O(n), where n is the length of the string since we traverse the string once.
Space Complexity: O(n), as in the worst case, the stack may need to store all characters.
1def remove_duplicates(s: str) -> str:
2 stack = []
3 for char in s:
4 if stack and stack[-1] == char:
5 stack.pop() # Remove last character
6 else:
7 stack.append(char) # Add current character
8 return ''.join(stack)
9
10print(remove_duplicates("abbaca"))
The solution uses a list as a stack to manage characters. It appends to the list, now simulating push operations, and pops the last element if an adjacent duplicate is found.
This approach also simulates stack behavior but uses a two-pointer technique on the same string to efficiently manage space without using additional data structures. It leverages the properties of strings and index manipulation to override adjacent duplicates.
Time Complexity: O(n), with n being the string length.
Space Complexity: O(1), since it modifies the original string in place.
1
The Python version uses a list to represent the string for direct modifications. The `i` pointer maintains the stack-like section of unique characters, and `j` runs through each character in the string. The index `i` is updated to simulate stack pops when duplicates are present.