Palindrome Linked List - Problem
Given the head of a singly linked list, determine if it represents a palindrome.
A palindrome reads the same forward and backward. For example, "racecar" or "madam" are palindromes. Your task is to check if the sequence of values in the linked list forms a palindrome when read from head to tail.
Goal: Return true if the linked list is a palindrome, false otherwise.
Challenge: Can you solve this in O(n) time and O(1) space?
Input & Output
example_1.py โ Simple Palindrome
$
Input:
head = [1,2,2,1]
โบ
Output:
true
๐ก Note:
The list reads as 1โ2โ2โ1, which is the same forwards and backwards, making it a palindrome.
example_2.py โ Not a Palindrome
$
Input:
head = [1,2]
โบ
Output:
false
๐ก Note:
The list reads as 1โ2, which is not the same when reversed (2โ1), so it's not a palindrome.
example_3.py โ Single Node
$
Input:
head = [1]
โบ
Output:
true
๐ก Note:
A single node is always considered a palindrome since it reads the same forwards and backwards.
Visualization
Tap to expand
Understanding the Visualization
1
The Two-Speed Race
Use a tortoise and hare approach: slow pointer moves one step, fast pointer moves two steps. When fast reaches the end, slow is at the middle.
2
The Great Reversal
Reverse the second half of the list, turning it into a mirror image that we can compare with the first half.
3
The Mirror Test
Compare nodes from the first half with the reversed second half, one by one, to check if they match perfectly.
Key Takeaway
๐ฏ Key Insight: By finding the middle and reversing half the list, we transform the palindrome check into a simple comparison between two forward-moving pointers, achieving optimal space complexity!
Time & Space Complexity
Time Complexity
O(n)
We traverse the list a few times but each traversal is O(n), so overall O(n)
โ Linear Growth
Space Complexity
O(1)
We only use a constant amount of extra space for pointers
โ Linear Space
Constraints
- The number of nodes in the list is in the range [1, 105]
- 0 โค Node.val โค 9
- Follow-up: Could you do it in O(n) time and O(1) space?
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code