Skip to problem
←

Palindrome Linked List

Easy 0 attempts

Given the head of a singly linked list, return true if its sequence of values reads the same forwards and backwards. Otherwise, return false.

Compare node values, not node identities. A one-node list is a palindrome. For example, [1, 2, 3, 2, 1] is a palindrome, while [1, 2, 3, 1] is not.

The examples display lists as value arrays, but your function receives linked nodes with val and next properties; the last node's next is null.

Follow-up: Can you solve this in linear time using constant extra space? The reference solution also restores the original list after checking it.

Function contract

Implement isPalindrome(head). Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.

Output: Return true if the list values form a palindrome; otherwise return false.

Example 1

Input
head = [1,2,2,1]
Output
true

Example 2

Input
head = [1,2]
Output
false
Constraints
  • 1 to 10^5 nodes
  • 0 <= Node.val <= 9

Reverse and Restore the Second Half

Find the end of the first half using a slow pointer and a pointer moving twice as fast. Reverse the list after that node, then compare its values with the first half. For odd lengths, the middle node is excluded from the reversed half because it does not need a partner.

Record the result without returning early on a mismatch. Reverse the second half again and reconnect it before returning, so both successful and unsuccessful checks preserve every original node and link.

javascript
function isPalindrome(head) {
  if (!head || !head.next) return true;
  function reverse(node) {
    let prev = null;
    while (node) {
      const next = node.next;
      node.next = prev;
      prev = node;
      node = next;
    }
    return prev;
  }
  let slow = head,
    fast = head;
  while (fast.next && fast.next.next) {
    slow = slow.next;
    fast = fast.next.next;
  }
  const second = reverse(slow.next);
  let left = head,
    right = second;
  let matches = true;
  while (right) {
    if (left.val !== right.val) {
      matches = false;
      break;
    }
    left = left.next;
    right = right.next;
  }
  slow.next = reverse(second);
  return matches;
}

Time: O(L) | Space: O(1), where L is the number of nodes. All traversals are iterative, including restoration.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript