Palindrome Linked List

EasyLinked List · Fast & Slow Pointers · In-place Reversal🧩 Linked List TechniquesLeetCode #234 ↗Updated

Problem

You get the head of a singly linked list of digits. Return true if the sequence of values reads the same forwards and backwards, otherwise false. You can only walk the list forwards.
Input[1,2,2,1]Outputtrue
Input[1,2]Outputfalse
Input[3,1,3]Outputtrue

1 ≤ n ≤ 105  ·  0 ≤ Node.val ≤ 9  ·  Follow-up: O(n) time and O(1) extra space.

Try it yourself

Java
class Solution {
    public boolean isPalindrome(ListNode head) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
A palindrome means the second half, read backwards, equals the first half. Find the middle with fast/slow pointers, reverse the second half in place, and the two halves can be compared walking forwards.
PatternLinked List Techniques

Instinct Nodes joined by next pointers and the task is to reverse, splice, merge, reorder or remove in place - grab a dummy head and rewire pointers carefully.

Memory hack Save next, flip, step - never let go of a rope before you've grabbed the next one.

Open the Linked List Techniques guide →

Approaches

Brute ForceCopy Values to an Array, Two Pointers

Time O(n)Space O(n)

Arrays allow walking from both ends, lists do not. Dump all values into an ArrayList, then move i from the left and j from the right, comparing as they meet in the middle.

Java
public boolean isPalindrome(ListNode head) {
    List<Integer> vals = new ArrayList<>();
    for (ListNode c = head; c != null; c = c.next) vals.add(c.val);
    int i = 0, j = vals.size() - 1;
    while (i < j) {
        if (!vals.get(i).equals(vals.get(j))) return false;
        i++;
        j--;
    }
    return true;
}

Simple and safe, but stores a full copy of the list.

At a glance

LevelApproachTimeSpace
Brute ForceCopy Values to an Array, Two PointersO(n)O(n)
BetterStack the First Half (Fast/Slow)O(n)O(n/2)
OptimalReverse the Second Half, Compare, RestoreO(n)O(1)
Common pitfalls
  • Comparing boxed Integers with == — works only for small values by caching luck.
  • Wrong middle for odd lengths — the centre node must be skipped (or ignored), not compared.
  • Breaking out of the compare loop before restoring the reversed half.
Interview tips
  • Start from the array copy, then ask whether O(1) space is required.
  • Explain why the fast/slow stop condition puts slow at the end of the first half.
  • Test aloud: single node, two equal nodes, two different nodes, odd length.
Pattern
Find middle + reverse half → compare or interleave the two halves of a singly linked list in O(1) space.
My notes saved in this browser