JSFiddle - React, Tailwind, and code Playground
by Prathameshsb
JavaScript
function removeAdjacentDuplicatesOfSizeN(s, n) {
const stack = [];
for (const char of s) {
if (stack.length >= n - 1) {
let count = 0;
for (let i = 0; i < n - 1; i++) {
if (char !== stack[stack.length - n + 1 + i]) {
break;
}
count++;
}
if (count === n - 1) {
stack.splice(-n + 1);
continue;
}
}
stack.push(char);
}
return stack.join('');
}
// Example
const inputString = "xyyxzx";
const n = 2;
const outputString = removeAdjacentDuplicatesOfSizeN(inputString, n);
console.log("Output:", outputString); // Output: "zx"