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:
slowmoves one step at a time,fastmoves two steps. - When
fastreaches the end,slowis 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, andnextto reverse the pointers one by one. - After reversal,
prevpoints to the head of the reversed second half.
4. Compare Both Halves
- Walk two pointers:
leftfrom the head andrightfrom the head of the reversed second half. - At each step, compare
left.valandright.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
—
Press play to start traversal
Slow (S)Fast (F)Both
7 steps