DEV Community

loading...

Discussion on: A coding interview question asked at Google

Collapse
karpour profile image
karpour

Got this recommended via Google and gave it a try :)

"use strict"

function checkEquivalentKeypresses(input) {
    // Reverse arrays for easier processing
    let a = input[0].split(",").reverse();
    let b = input[1].split(",").reverse();
    // Function to return index of the next not-deleted character
    let nextChar = (arr, idx) => {
        let bc = 0; // Backspace counter
        let i = idx; // Start index
        // Loop until a regular character is found with bc=0
        // If the character at idx is a regular character, the loop is skipped
        for (; i < arr.length && !(bc == 0 && arr[i].length == 1); i++) { 
            bc += (arr[i].length > 1 ? 1 : -1); 
        }
        // If bc is 0 and the character at i is defined and not a backspace, return that i
        // Otherwise it means the end of the array is reached, return undefined
        return (bc == 0 && arr[i] != undefined && arr[i].length == 1) ? i : undefined;
    }
    let nextcharA = nextChar(a, 0); // Get first character
    let nextcharB = nextChar(b, 0); // Get first character
    // Loop as long as the characters are the same
    for (let i = 0; !(nextcharA == undefined || nextcharB == undefined) && b[nextcharB] == a[nextcharA]; i++) {
        nextcharA = nextChar(a, nextcharA + 1);
        nextcharB = nextChar(b, nextcharB + 1);
        //console.log("a: " + a[nextcharA]);
        //console.log("b: " + b[nextcharB]);
    }
    // If both strings are equivalent, they will get set to undefined at the same point

    return nextcharA == undefined && nextcharB == undefined;
}
Collapse
elisabethgross profile image
elisabethgross Author

Nice! Glad you found us :)