JSFiddle - React, Tailwind, and code Playground

by Prathameshsb

JavaScript

var removeConsecutiveDuplicates = function(board) {
    let stack = [];
    let changed = true;

    while (changed) {
        changed = false;
        stack = [];

        for (let i = 0; i < board.length; i++) {
            if (stack.length > 0 && stack[stack.length - 1][0] === board[i]) {
                stack[stack.length - 1][1]++; // Increment count of the top stack element
                if (stack[stack.length - 1][1] >= 3) {
                    stack.pop(); // Remove the group from the stack
                    changed = true; // Indicate that a removal occurred
                }
            } else {
                stack.push([board[i], 1]); // Push new character with count 1
            }
        }

        // Rebuild the board from the stack
        board = stack.map(([char, count]) => char.repeat(count)).join('');
    }

    return board;
};

// Example usage
console.log(removeConsecutiveDuplicates("abbba")); // Output: ""
console.log(removeConsecutiveDuplicates("aabbbacc")); // Output: "c"