Palindrome Linked List
Check if a linked list reads the same both ways in O(1) space: find the middle, reverse half, compare.
The problem
You get the head of a singly linked list. Return true if its values read the same from front to back as from back to front, and false otherwise. Try to use only O(1) extra space.
Input head = [3, 7, 0, 7, 3]
Output true
Read backwards, the values are again 3, 7, 0, 7, 3.
Input head = [5, 2, 2, 8]
Output false
The first value is 5 but the last one is 8.
Key constraint: Up to 100,000 nodes, and the follow-up asks for O(1) extra space, so you can't copy the values into an array.
How to spot the pattern
- You must compare the first half of a list with the second half read backwards.
- A singly linked list can't walk backwards, and copying it would cost O(n) space.
The idea
In a palindrome, the second half read backwards is exactly the first half. A singly linked list can't be read backwards, but you can reverse its second half in place. So find the middle with slow and fast pointers, reverse everything after it, and walk the two halves side by side comparing values; at the end, reverse the second half back so the caller gets the list unchanged.
Brute force: Copy the values into an array and compare it with its reverse, which is O(n) time but O(n) extra space.
Step by step
- 1Find the end of the first half: move
slowone step andfasttwo steps whilefast.nextandfast.next.nextexist. - 2Reverse the part of the list after
slow. - 3Walk from
headand from the start of the reversed half together, comparing values until the reversed half runs out. - 4Reverse the second half again and attach it after
slow, so the list is as it was. - 5Return
falseif any pair of values differed, otherwisetrue.
See the pattern move
The fast and slow pointers pattern on a small example. Step through it, or press play.
Code
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
if head is None:
return True
# 1. Find the middle: slow stops at the last node of the first half.
slow = fast = head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
# 2. Reverse the second half.
second = self.reverse(slow.next)
# 3. Compare the first half with the reversed second half.
result = True
first, rest = head, second
while rest:
if first.val != rest.val:
result = False
break
first = first.next
rest = rest.next
# 4. Reverse the second half back, so the list is unchanged.
slow.next = self.reverse(second)
return result
def reverse(self, node: Optional[ListNode]) -> Optional[ListNode]:
prev = None
while node:
nxt = node.next
node.next = prev
prev = node
node = nxt
return prevComplexity
Time
O(n)
Space
O(1)
Finding the middle, reversing, comparing and restoring each walk at most the whole list once, with a few pointers.
Watch out for
- Comparing node objects instead of their values: the two halves are different nodes, so compare
val. - Comparing until the first half runs out: for odd lengths the first half still holds the middle node, so stop when the reversed half ends.
- Leaving the input list broken: if the caller uses the list afterwards, reverse the second half back before you return.
Follow-up questions
Can you solve it with recursion?
Yes: recurse to the end of the list while a pointer from the front waits outside the recursion, then compare on the way back and move the front pointer one step each time. It is short, but the call stack uses O(n) space.
What if you are not allowed to change the list at all, even for a moment?
Then the reversal trick is off the table. Push the first half's values onto a stack (or copy all values into an array) and compare, which uses O(n) space.
In Hinglish
Beech dhoondo, doosra half ulta karo, phir dono halves ki values saath-saath compare karo. Kaam ho jaaye toh list ko wapas seedha kar dena.