sagelearnai

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          →  false

Hints

  1. Copying the values into an array is O(n) space. To stay O(1), compare the first half with the reversed second half.
  2. Fast/slow pointers find the middle in one pass.

Approach

  1. Middle: slow moves 1 step and fast moves 2. When fast reaches the end, slow is at the middle (for odd lengths, the middle node is skipped naturally).
  2. Reverse the list from slow onward.
  3. Compare node by node from head and from the reversed half's head.
  4. (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 True
JavaScript 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;
}