Coding Interview PatternsPalindrome Linked List
EasyFast and Slow Pointers

Palindrome Linked List

Explanation & Solution

Description

Given the head of a singly linked list, return true if it is a palindrome, or false otherwise.

You must solve it in O(n) time and O(1) space.

Input:head = [1,2,2,1]
0
1
1
2
2
2
3
1

Output: true

Explanation: The values read the same forwards and backwards: 1 → 2 → 2 → 1.

Constraints

  • The number of nodes in the list is in the range [0, 10⁵]
  • 0 <= Node.val <= 9

Approach

Fast and Slow Pointers pattern

1. Handle Edge Cases

  • If the list is empty or has only one node, it is trivially a palindrome — return true.

2. Find the Middle of the List

  • Use two pointers: slow moves one step at a time, fast moves two steps.
  • When fast reaches the end, slow is at the middle (or just before the second half for even-length lists).

3. Reverse the Second Half

  • Starting from slow.next, reverse the linked list in-place.
  • Use three variables: prev, curr, and next to reverse the pointers one by one.
  • After reversal, prev points to the head of the reversed second half.

4. Compare Both Halves

  • Walk two pointers: left from the head and right from the head of the reversed second half.
  • At each step, compare left.val and right.val.
  • If any pair differs, the list is not a palindrome — return false.
  • If all pairs match, return true.

Key Insight

  • By reversing only the second half, we can compare the list from both ends without using extra space.
Time
O(n)finding the middle is O(n), reversing is O(n), comparing is O(n).
Space
O(1)only a constant number of pointer variables are used.

Visualization

Input:
Linked List Traversal
10212213null

Press play to start traversal

Slow (S)Fast (F)Both
7 steps

Solution Code