EasyPythonJavaScriptTypeScript
Linked List — Palindrome List in O(1) Space
Data StructuresLinked ListTwo Pointers
solve(values) builds a singly linked list from values and returns true when it
reads the same forwards and backwards. An empty list is a palindrome.
Copying the values into an array is O(n) space. Do better by combining two earlier ideas:
find the middle with slow / fast pointers, reverse the second half in place, then
walk the first half and the reversed second half together comparing values.
Examples
solve([1,2,2,1]) → true
solve([1,2,3,2,1]) → true
solve([1,2]) → falseSample tests
Test #1Even palindrome
Input: [[1,2,2,1]]
Output: true
Test #2Odd palindrome
Input: [[1,2,3,2,1]]
Output: true
Test #3Not a palindrome
Input: [[1,2]]
Output: false