Created
December 15, 2020 14:27
-
-
Save iJustErikk/ee51364855597698f16d1e2ec425bb08 to your computer and use it in GitHub Desktop.
For medium article.
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
// checks two moving indices and stops when needed | |
const isPalindrome = (arr) => { | |
// symmetry will always be found in one or 0 elements | |
// [1] -> true | |
// [] -> true | |
if (arr.length < 2) return true; | |
// taking two pointer approach | |
let first = 0; | |
let last = arr.length - 1; | |
while (first < last) { | |
// if symmetry is broken, stop RIGHT there | |
if (arr[first] !== arr[last]) return false; | |
// walk our pointers | |
first += 1; | |
last -= 1; | |
} | |
// if symmetry is unbroken throughout string | |
// string is symmetrical | |
return true; | |
}; | |
const checkPalindromes = () => { | |
// should be true, true, false, true, false, true | |
const toCheck = [[], [3], [1, 3], [1, 1], [1, 2, 3], [1, 2, 1]]; | |
const expections = [true, true, false, true, false, true]; | |
toCheck.forEach((item, idx) => { | |
console.assert(isPalindrome(item) === expections[idx]); | |
}); | |
console.log("Passed test cases!") | |
} | |
checkPalindromes(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment