Skip to content

Latest commit

 

History

History
39 lines (31 loc) · 1.26 KB

File metadata and controls

39 lines (31 loc) · 1.26 KB

You are given a string s and an integer k, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together.

We repeatedly make k duplicate removals on s until we no longer can.

Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique.

Screen Shot 2021-11-12 at 00 48 20

Time complexity: O(n), where nn is a string length. We process each character in the string once.

Space complexity: O(n) for the stack.

/**
 * @param {string} s
 * @param {number} k
 * @return {string}
 */
var removeDuplicates = function(s, k) {
    let stack = [];
    
    for(let c of s) {
        if(stack.length && stack[stack.length - 1][0] === c) {
            stack[stack.length - 1][1] += 1;
            if(stack[stack.length - 1][1] === k) {
                stack.pop();
            }
        } else {
            stack.push([c, 1]);
        }
    }
    
    let res = "";
    
    for(let [c, count] of stack) {
        res += c.repeat(count);
    }
    return res;
};