Palindrome Linked List Problem
#234
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 234. Given a singly linked list, determine if it is a palindrome.
Example:
Input: 1->2
Output: false
Input: 1->2->2->1
Output: true
Solution
Approach: Reverse the Second Half
Copying the values into an array and checking that works, but takes O(n) extra space. We can compare in place instead: a singly linked list can only be walked forward, so reverse its second half, then walk both halves forward together.
- Find the middle with a slow and a fast pointer.
slowmoves one node per step andfasttwo. Whenfastreaches the end,slowis at the start of the second half (the middle node itself when the length is odd). - Reverse the list from
slowwith the usual three-pointer reversal.prevends up at the old last node. - Compare nodes from
headand fromprev, moving both forward, until the reversed half runs out. Any mismatch means the list is not a palindrome.
1 -> 2 -> 3 -> 2 -> 1 slow stops at 3
1 -> 2 -> 3 <- 2 <- 1 after reversing from 3
head ^ ^ prev
For an odd length the middle node ends up in the reversed half and is compared with itself, so it needs no special case. Stop when the reversed half runs out: the first half is never shorter. This modifies the list; reverse the second half again afterwards if the caller needs it intact.
Complexity: O(n) time and O(1) extra space, where n is the number of nodes.
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
# 1. Find the middle: fast moves two nodes per step, slow one node.
slow = fast = head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
# slow is now the first node of the second half (the middle node when the length is odd).
# 2. Reverse the second half.
prev = None
while slow is not None:
next_node = slow.next
slow.next = prev
prev = slow
slow = next_node
# 3. Compare the first half with the reversed second half.
left, right = head, prev
while right is not None:
if left.val != right.val:
return False
left = left.next
right = right.next
return True
Now write it from memory
Close the write-up and solve it yourself against the tests.