DEV Community

loading...

Discussion on: A coding interview question asked at Google

Collapse
firee80 profile image
Firee80

This solution allows n-amount of inputs and uses Set to check all items are the same.

function checkEquivalentKeypresses(...keyPressLines) {
  const keyPressArrays = keyPressLines.map(keyPressLine => keyPressLine.split(','))
  const keyPressArraysWithoutBackspace = keyPressArrays.map(array =>
    array.reduce((result, letter) => letter === '-B' ? [...result].slice(0, -1) : [...result, letter], []))
  const keyPressLinesWithoutBackspace = keyPressArraysWithoutBackspace.map(array => array.join(''))  
  return keyPressLines.length > 1 ? (new Set(keyPressLinesWithoutBackspace)).size === 1 : false  
}

console.log(checkEquivalentKeypresses(...['a,b,c,d', 'a,b,c,c,-B,d'])) // true
console.log(checkEquivalentKeypresses(...['-B,-B,-B,c,c', 'c,c'])) // true
console.log(checkEquivalentKeypresses(...['', 'a,-B,-B,a,-B,a,b,c,c,c,d'])) // false
Collapse
elisabethgross profile image
Collapse
firee80 profile image
Firee80

made the function to support also other data types of input..
changed naming and simplified return statement (new Set() is not ran if result.length > 1 fails first).

function checkEquivalentKeypresses(...lines) {
  const linesSplit = lines.some(line => typeof(line) !== 'string') ? [] : lines.map(line => line.split(','))
  const linesNoBackspace = linesSplit.map(lineArray =>
    lineArray.reduce((result, key) => key === '-B' ? [...result].slice(0, -1) : [...result, key], []))
  const result = linesNoBackspace.map(array => array.join(''))
  return result.length > 1 && (new Set(result)).size === 1  
}

console.log(checkEquivalentKeypresses(...['a,b,c,d', 'a,b,c,c,-B,d'])) // true
console.log(checkEquivalentKeypresses(...['-B,-B,-B,c,c', 'c,c'])) // true
console.log(checkEquivalentKeypresses(...['', 'a,-B,-B,a,-B,a,b,c,c,c,d'])) // false
console.log(checkEquivalentKeypresses(NaN,{})) // false
console.log(checkEquivalentKeypresses('a,b,c','a,b,c,d,-B')) // true
Collapse
dmadden51 profile image
David Madden

Doesn't Set remove duplicates?

Thread Thread
firee80 profile image
Firee80

yes.. that is why end result size should be 1
[1,1,1] => [1]
the code checks first that the initial array has more than 1 input so
[1] => [1]
would fail on the first length check