JSFiddle - React, Tailwind, and code Playground

by Prathameshsb

JavaScript

var removeAllConsecutiveGroups = function(s) {
    let stack = [];

    for (let char of s) {
        // If stack is not empty and the top character is the same as the current character
        if (stack.length > 0 && stack[stack.length - 1].char === char) {
            stack[stack.length - 1].count += 1; // Increment count
        } else {
            stack.push({ char, count: 1 }); // Push new character with count 1
        }

        // If we detect a streak, remove all occurrences of that character
        if (stack.length > 0 && stack[stack.length - 1].count >= 2) {
            stack.pop();
        }
    }

    // Reconstruct the final string
    let result = "";
    for (let item of stack) {
        result += item.char.repeat(item.count);
    }

    return result;
};

// Example Test Cases
console.log(removeAllConsecutiveGroups("abbba")); // Output: ""
console.log(removeAllConsecutiveGroups("abccba")); // Output: ""
console.log(removeAllConsecutiveGroups("aabbccddeeffgghhii")); // Output: ""
console.log(removeAllConsecutiveGroups("abcde")); // Output: "abcde"
console.log(removeAllConsecutiveGroups("aaabbbaaa")); // Output: ""
console.log(removeAllConsecutiveGroups("abbaabba")); // Output: ""
console.log(removeAllConsecutiveGroups("aabbccddeeffgg")); // Output: ""
console.log(removeAllConsecutiveGroups("aabbaabb")); // Output: ""