Palindrome Linked List
Difficulty: Easy · Pattern: Fast & Slow Pointers · LeetCode #234
Return true if the singly linked list reads the same forwards and backwards. Follow-up: O(n) time and O(1) extra space.
Examples
text
1 → 2 → 2 → 1 → true
1 → 2 → falseHints
- Copying the values into an array is O(n) space. To stay O(1), compare the first half with the reversed second half.
- Fast/slow pointers find the middle in one pass.
Approach
- Middle:
slowmoves 1 step andfastmoves 2. When fast reaches the end, slow is at the middle (for odd lengths, the middle node is skipped naturally). - Reverse the list from
slowonward. - Compare node by node from
headand from the reversed half's head. - (Good practice) reverse the second half again to restore the input.
This one problem combines three linked-list primitives: middle finding, reversal and two-pointer walking.
Complexity
Time: O(n). Space: O(1).
Python solution
def isPalindrome(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
prev = None
while slow:
slow.next, prev, slow = prev, slow, slow.next
a, b = head, prev
while b:
if a.val != b.val:
return False
a, b = a.next, b.next
return TrueJavaScript solution
function isPalindrome(head) {
let slow = head, fast = head;
while (fast && fast.next) { slow = slow.next; fast = fast.next.next; }
let prev = null;
while (slow) { const nx = slow.next; slow.next = prev; prev = slow; slow = nx; }
for (let a = head, b = prev; b; a = a.next, b = b.next) if (a.val !== b.val) return false;
return true;
}