Last active
April 20, 2016 03:27
-
-
Save chrisrng/d870ccf25031efaba43137c9a0d2b52e to your computer and use it in GitHub Desktop.
My answer to https://www.reddit.com/r/cscareerquestions/comments/4evk44/my_google_tech_interviewing_decoded_experience/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Longest(matrix) { | |
const cache = getMarkedUpMatrix(matrix); | |
let current = 1; | |
let longest = 1; | |
Object.keys(cache).map((value) => { | |
const cacheObj = cache[value]; | |
const cacheObj2 = cache[(parseInt(value, 10) + 1) + '']; | |
if (isNeighbor(cacheObj, cacheObj2)) { | |
current++; | |
if (current > longest) { | |
longest = current; | |
} | |
} else { | |
current = 1; | |
} | |
}); | |
return longest; | |
} | |
function getMarkedUpMatrix(matrix) { | |
const cache = {}; | |
const markedupMatrix = matrix.map((row, rowIndex) => { | |
return row.map((colValue, colIndex) => { | |
cache[colValue] = {col: colIndex, row: rowIndex}; | |
}); | |
}); | |
return cache; | |
} | |
function isNeighbor(first, second) { | |
if (!first || !second) { return false; } | |
const x1 = first.row; | |
const x2 = first.col; | |
const y1 = second.row; | |
const y2 = second.col; | |
const y1range = Boolean([y2 - 1, y2, y2 + 1, y2 + 2].includes(y1)); | |
const x1range = Boolean([y1 - 1, y1, y1 + 1, y1 + 2].includes(x1)); | |
return Boolean((x1 === y1 && y1range ) || (x2 === y2 && x1range)); | |
} | |
console.log(Longest([[0, 1, 4], [2, 3, 5], [8, 7, 6]])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment