LeetCode #234 Medium

Palindrome Linked List

Given the head of a singly linked list, return true if it reads the same forwards and backwards — using O(1) extra space.

linked listtwo pointersstack
Open on LeetCode ↗
02

Intuition

💡

You can't walk a singly linked list backwards. So find the middle, reverse the second half in place, then walk the two halves toward each other comparing values. Equal all the way means palindrome.

03

Approach

1

Find the middle with slow / fast

Run a slow pointer one step and a fast pointer two steps. When fast reaches the end, slow sits at the midpoint — the start of the second half. This is the same tortoise-and-hare trick used for 'Middle of the Linked List'.

2

Reverse the second half in place

From slow, reverse the rest of the list using the standard prev/curr pointer flip. Now you have two half-lists: the original front half (still pointing forward) and the reversed back half. No extra array is needed, so space stays O(1).

3

Walk both halves and compare

Advance one pointer from the head and one from the reversed second half, comparing values node by node. If any pair differs, return false immediately; if you exhaust the shorter half with all matches, it's a palindrome — return true. (The middle node in an odd-length list is ignored, which is correct.)

04

Solution & live demo

python
1class Solution:
2 def isPalindrome(self, head):
3 slow = fast = head
4 while fast and fast.next:
5 slow = slow.next
6 fast = fast.next.next
7 prev = None
8 while slow:
9 slow.next, prev, slow = prev, slow, slow.next
10 left, right = head, prev
11 while right:
12 if left.val != right.val:
13 return False
14 left = left.next
15 right = right.next
16 return True
05

Edge cases

Empty list or single node

Trivially a palindrome — return true.

Even vs odd length

For odd length the middle node is unpaired and safely skipped; comparison only spans the matched halves.

Restoring the list

If the caller needs the list intact afterward, reverse the second half back; the comparison itself only needs it reversed.

06

Complexity

Time
O(n)
Space
O(1)
One pass to the middle, one to reverse, one to compare; only a few pointers of extra space.