LeetCode #234 Easy

Palindrome Linked List

Palindrome Linked List is LeetCode 234 (Easy). Given the head of a singly linked list, return true if its values read the same from front to back as from back to front.

  • The list has at least one node, and a single node is a palindrome.
  • A singly linked list can only be walked forwards, so the back of the list cannot be read directly the way an array can.
  • The follow-up asks for O(n) time and O(1) extra space, which rules out copying the values.
Constraints
  • The number of nodes in the list is in the range [1, 10⁵].
  • 0 <= Node.val <= 9
linked listtwo pointersstack
Open on LeetCode ↗
02

Intuition

A palindrome is a list whose first half mirrors its second half. The trouble is that the second half can only be read forwards, while the comparison needs it backwards.

So reverse the second half in place, and it reads backwards for free. Then walk one pointer from the head and one from the far end, comparing values until the reversed half runs out.

  • Finding the middle: a slow pointer moving one node and a fast pointer moving two. When fast runs out, slow is at the start of the second half.
  • Odd length: the middle node lands in the reversed half and is compared with itself, which always matches.
How to spot this pattern

"Compare the front of a linked list with its back" in O(1) space means: find the middle with slow and fast pointers, reverse one half, and walk the two halves together.

03

Approach

Try it first

Before reading on, ask what stops you comparing the first and last nodes directly, then which half you could change so it can be read the other way. Aim for O(n) time and O(1) extra space.

1

Find the middle with slow and fast pointers

Start both at the head. While fast and fast.next exist, move slow one node and fast two. Fast covers the list twice as quickly, so when it stops, slow has reached the first node of the second half.

2

Reverse the second half

Reverse the nodes from slow to the end with the usual three-pointer loop. It returns the old last node, which is now the start of a chain that runs back towards the middle.

3

Compare the two halves

Walk left from the head and right from the reversed start, one node each per round. Stop at the first pair of unequal values. Loop on right because the reversed half is never longer than the first half plus the middle node.

4

Reverse the second half back

Reverse the same chain again before returning. The caller handed over the list and may use it afterwards, so leaving half of it backwards would be a hidden side effect.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def isPalindrome(self, head: Optional[ListNode]) -> bool:
▶3 slow = fast = head
▶4 while fast and fast.next:
▶5 slow = slow.next
▶6 fast = fast.next.next
▶7 tail = self.reverse(slow)
▶8 left, right, ok = head, tail, True
▶9 while right:
▶10 if left.val != right.val:
▶11 ok = False
▶12 break
▶13 left, right = left.next, right.next
▶14 self.reverse(tail)
▶15 return ok
▶16 
▶17 def reverse(self, node: Optional[ListNode]) -> Optional[ListNode]:
▶18 prev = None
▶19 while node:
▶20 nxt = node.next
▶21 node.next = prev
▶22 prev, node = node, nxt
▶23 return prev
1221slowfastlistslow and fast both start at the first node
slownode 1
fastnode 1
Fast will take two steps for every one step of slow. When fast can go no further, slow has covered half the distance, which is where the back half begins.
1221slowfastlistslow → node 2, fast → node 3
slownode 2
fastnode 3
Both pointers move. Fast can still take two more steps, so the loop goes on.
1221slowfast: off the endlistfast cannot jump again → back half starts at node 3
slownode 3
fastnone
Fast ran off the end, so the length is even and slow sits on the first node of the back half.
1221back half: nodes 3 to 42 (node 3) now points to nothing
node3
points tonone
The first node of the back half becomes the end of the reversed chain, so its next pointer is cleared. The node before it still points to it, which is fine: that link is never followed backwards.
1221back half: nodes 3 to 41 (node 4) now points back to node 3
node4
points tonode 3
Node 4 is turned around to point at node 3. Its old next was saved first, so the rest of the half is not lost.
1221leftrightback half: nodes 3 to 41 = 1 → move both inward
left1
right1
Node 1 and node 4 mirror each other and match. Left moves forward, right follows the reversed arrows towards the middle.
1221leftrightback half: nodes 3 to 42 = 2 → move both inward
left2
right2
Node 2 and node 3 mirror each other and match. Left moves forward, right follows the reversed arrows towards the middle.
1221back half: nodes 3 to 4back half reversed again → list as given
result so fartrue
Reversing the same chain a second time turns every arrow forwards again, so the caller gets back the list it passed in, not a list with its back half facing the wrong way.
1221listanswer: true
returntrue
Every pair from the two ends matched, so the values read the same both ways.
05

Copy the values into an array

Walk the list once and store each value. An array can be read from both ends, so two indices move towards each other and stop at the first mismatch.

▶1class Solution:
▶2 def isPalindrome(self, head: Optional[ListNode]) -> bool:
▶3 vals = []
▶4 while head:
▶5 vals.append(head.val)
▶6 head = head.next
▶7 i, j = 0, len(vals) - 1
▶8 while i < j:
▶9 if vals[i] != vals[j]:
▶10 return False
▶11 i, j = i + 1, j - 1
▶12 return True
06

Common pitfalls

Returning before the list is put back

✗ Wrong
if left.val != right.val:
    return False
✓ Right
if left.val != right.val:
    ok = False
    break

An early return skips the second reversal. For [1, 2, 3, 4] the first pair already differs, so the function returns with 4 pointing back at 3 and 3 pointing at nothing. Reading the list from the head afterwards gives only 1 → 2 → 3.

Looping on left instead of right

✗ Wrong
while left:
✓ Right
while right:

The first half still points into the reversed half, so left has more nodes to visit than right. For [1, 2, 2, 1] the right side runs out after two rounds while left is still on the second 2, and reading right.val on null crashes.

07

Edge cases

A single node

The fast pointer cannot move, so the second half is that one node. It is compared with itself and the answer is true.

08

Complexity

Time
O(n)
Space
O(1)
Finding the middle reads about n/2 nodes, each reversal reads n/2, and the comparison reads up to n/2, so the work is a small constant times n. Only a handful of pointers are stored.
09

Palindrome Linked List FAQ

Can recursion check it without reversing anything?

Yes. Recurse to the end of the list and compare each node on the way back with a front pointer that moves forward. It leaves the list untouched, but the call stack holds n frames, so it is O(n) space and can overflow at 10⁵ nodes.