DEV Community

Discussion on: A common coding interview question

Collapse
 
firee80 profile image
Firee80

simplified the solution by using Sets and corrected the answer to correspond the assignment

const lines = ['1,2,3,4,5,6', '2,4,6,7,8,9,10', '1,2,3,4,5,6,8']

function FindIntersection(lines) {
  const getSet = line => new Set(line.split(',').map(number => parseInt(number)))
  const [firstSet, ...otherSets] = lines.map(getSet)
  const result = [...otherSets.reduce((lastSet, set) => new Set([...set].filter(number => lastSet.has(number))), firstSet)]
  return result.length > 0 ? result : 'false'
}

console.log(FindIntersection(lines)) // outputs: [2,4,6]