You are given the first node, head, of a singly linked list. Each node holds one digit and a link to the next node.
Return true if the values read the same from the last node back to the first as they do from the first node forward, and false if they do not.
Example 1
Input: head = [4, 7, 7, 4] Output: true Why: backwards it is still 4, 7, 7, 4
2 more examples and the constraints
Example 2
Input: head = [3, 8] Output: false Why: backwards it is 8, 3
Example 3
Input: head = [5, 0, 9, 0, 5] Output: true Why: the middle 9 has no partner to match
Constraints
- 1 ≤ number of nodes ≤ 100,000
- 0 ≤ each node's value ≤ 9
- Follow-up: can you use O(n) time and only O(1) extra memory?
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Copy into an arrayO(n)
- Reverse the second halfO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 nodes | Verdict |
|---|---|---|---|
| Copy into an array | O(n) | Passes; uses O(n) memory | |
| Reverse the second half | O(n) | Best; meets the O(1) follow-up |
n = number of nodes in the list. Both are linear; they differ in memory.
Edge cases to test
- One node. [6] is a palindrome:
fastnever moves and the reversed half is that single node. - Two different nodes. [3, 8] must give false; the first comparison catches it.
- Odd length. In [5, 0, 9, 0, 5] the middle 9 has no partner, and comparing it with itself is harmless.
- Mismatch next to the middle. [1, 2, 3, 1] only fails on the inner pair, so stopping after the outer pair is wrong.
Common mistakes
- Stopping
fastone node too early or late, so the two halves are off by one on even lengths. - Walking until
leftis null instead ofright; the first half still links into the second and runs too far. - Losing the rest of the list while reversing by setting
slow.nextbefore saving it.
How to talk through it
- 1Clarify. Can I change the list? Is a one-node list a palindrome? Do you want O(1) extra space?
- 2Give the simple version. Copy values into an array and compare from both ends: O(n) time and O(n) space.
- 3Find the middle. Slow and fast pointers find it in one walk, without counting the length.
- 4Reverse and compare. Reverse the second half in place, then walk both halves side by side.
- 5Test out loud. Run [6], [3, 8] and an odd-length case before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?