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.
1function removeDuplicates(s) {
2 const stack = [];
3 for (let char of s) {
4 if (stack.length && stack[stack.length - 1] === char) {
5 stack.pop(); // Remove last character
6 } else {
7 stack.push(char); // Add current character
8 }
9 }
10 return stack.join('');
11}
12
13console.log(removeDuplicates("abbaca"));
JavaScript arrays act as stacks, so elements are pushed or popped based on whether the current character is the same as the one at the end of the stack, representing adjacent duplicates in the string.
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 two-pointer method directly modifies the input string array by using `i` as the effective end of the currently processed string. Whenever a duplicate is detected, we backtrack the `i` pointer, simulating a pop operation. This way, space usage is minimized as no extra stack structure is created.