A palindrome reads the same forwards and backwards. With an array, you compare elements from both ends moving inward. A singly linked list only allows traversal in one direction, so there is no way to walk backwards from the tail.
The core challenge is comparing elements from the front and back of a structure that only supports forward traversal. Two approaches handle this: copy the values into an array that does support random access, or find the middle and reverse the second half in place to compare it against the first.
[1, 10^5]. With up to 100,000 nodes, any O(n^2) comparison would be too slow, so the target is O(n) time.0 <= Node.val <= 9. Values are single digits, so there is no overflow concern when comparing them.Copy all the node values into an array, then run the standard two-pointer palindrome check. An array supports random access, so comparing from both ends is direct.
This converts the linked list problem into an array problem, which sidesteps the lack of backward traversal at the cost of extra memory.
left starting at index 0 and right starting at the last index.left and right. If they differ, return false.left forward and right backward. Repeat until they meet or cross.true.This uses O(n) extra space for the array. The next approach removes that array by rearranging the list itself.
If we find the middle of the linked list, we can reverse the second half in place and then compare both halves node by node, using no extra array.
To find the middle, advance a slow pointer one step and a fast pointer two steps at a time. When fast reaches the end, slow sits at the start of the second half. Reversing the list from slow onward lets us walk the first half forward and the reversed second half forward at the same time, comparing values as we go.
When fast moves twice as fast as slow, slow reaches the start of the second half after fast has covered the whole list. For an even length the two halves have equal size; for an odd length the second half (starting at slow) has one extra node, the middle. The comparison loop runs while right != null, so it stops once the reversed second half is exhausted. For an odd list like [1, 2, 3, 2, 1], slow stops at the middle node (val 3), and the reversed second half becomes 1 → 2 → 3. The loop compares the first half 1, 2, 3 against 1, 2, 3, so the middle node is compared against itself and never breaks the palindrome. Because right (the shorter or equal half) controls the loop, left is never advanced past the list end.
false. If all match, return true.