Sponsored
Sponsored
This approach utilizes a stack data structure to track characters and their counts. As we iterate through the string, we push characters with their current counts on the stack. When the count of the top character in the stack reaches k
, we pop the character from the stack to simulate removal of duplicates.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n), for the stack and auxiliary storage.
1function removeDuplicates(s, k) {
2 const stack = [];
3 for (const char of s) {
4 if (stack.length && stack[stack.length - 1][0] === char) {
5 stack[stack.length - 1][1] += 1;
6 } else {
7 stack.push([char, 1]);
8 }
9 if (stack[stack.length - 1][1] === k) {
10 stack.pop();
11 }
12 }
13 return stack.map(pair => pair[0].repeat(pair[1])).join('');
14}
15
16// Example usage:
17console.log(removeDuplicates("deeedbbcccbdaa", 3)); // "aa"
18
This JavaScript solution employs an array to simulate a stack, where each element is a pair comprising a character and its streak count. The function efficiently concatenates the remaining characters to form the result string.
This approach utilizes a two-pointer technique to modify the string in place. Here, we treat the string as a character array, using one pointer to scan the input and another to build the output string. A helper array is used to store counts of consecutive characters.
Time Complexity: O(n)
Space Complexity: O(n)
1
This Python solution modifies the string in-place as much as possible. The characters are adjusted in a list and only the resulting string part up to the valid index j
is considered for output.