Palindrome Linked List – Solution & Complexity
1. Understand the Goal
- A linked list is a palindrome when its node values read the same forwards and backwards.
- The interview challenge is doing this in
O(1)extra space — you cannot index into a linked list, and copying all values to an array usesO(n)space. - The trick is to reverse only the second half in place and compare it against the first half.
2. Find the Middle with Fast/Slow Pointers
- Advance a
slowpointer one node at a time and afastpointer two nodes at a time. - When
fastreaches the end,slowsits at the middle of the list. - With the array framing, the same idea is a midpoint index
len(head) // 2.
3. Reverse the Second Half and Compare
- Reverse the second half of the list (in the real linked-list version this is an in-place pointer reversal).
- Walk both halves in step and compare values; if any pair differs, it is not a palindrome.
- An odd-length middle element can be ignored because it mirrors itself.
4. Final Complete Solution
- Finding the middle, reversing the second half, and comparing each take a single pass, so the total time is
O(n). - The in-place reversal keeps extra space at
O(1)for a true linked list. With the array framing, a symmetric two-pointer scan is the simplest correct approach.