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
This JavaScript technique similarly leverages array slicing coupled with two-pointer logic. The list is modified in place, ensuring the solution is as tight as possible without separate stacks.