DEV Community

loading...

Discussion on: A coding interview question asked at Google

Collapse
scott_yeatts profile image
Scott Yeatts • Edited

Not the "code golf" solution, but I think is more readable and avoids nested looping (plus I think the ternaries are more readable once they get a little long using multiple lines).

"Clever" solutions are fun... maintainable ones save time :D

If you wanted to split this out to handle multiple cases or non-compliant arrays (say with spaces or non-string content) I would add additional functions to handle those cases, but not as the spec exists now.

Localization for non-English languages could be handled by adding a language code param to the function or a constant.

function EquivalentKeypresses(strArr) { 

  // code goes here  
  const comparatorString = strArr[1].split(',')
    .reduce((agg, current) => {
      return current === '-B'
        ? agg.substring(0, agg.length - 1)
        : agg + current; 
    }, '');

  return strArr[0].localeCompare(comparatorString, 'en', {ignorePunctuation: true}) === 0;
}

// keep this function call here 
console.log(EquivalentKeypresses(readline()));
Collapse
scott_yeatts profile image
Scott Yeatts • Edited

Changed, only cause when I submitted on coderbyte, the test cases showed that "-B" cases were possible in the first string (IE: comparing vs an edited string as opposed to a base-string, so... egg on my face haha)

(And I edited again... because code review matters, and there's code to be removed...)

Here's the modified solution:

function compare(str) {
  return str.split(',')
    .reduce((agg, current) => {
      return current === '-B'
        ? agg.substring(0, agg.length - 1)
        : agg + current; 
    }, '');
}

function EquivalentKeypresses(strArr) { 

  // code goes here 
  return compare(strArr[0]).localeCompare(compare(strArr[1]),'en',{ignorePunctuation: true}) === 0;
}

// keep this function call here 
console.log(EquivalentKeypresses(readline()));