Write code that will check if a linked list is a palindrome or not.
💡Strategies for Solving This Problem
The Problem
I got this question at Meta and initially froze. A palindrome linked list reads the same forwards and backwards: 1→2→2→1 is a palindrome, 1→2→3 isn't. The tricky part? You can't just index backwards like with an array.
Approach 1: Reverse and Compare (What I Used)
The insight: if the list is a palindrome, the first half equals the reversed second half.
- Find the middle using slow/fast pointers
- Reverse the second half
- Compare first half with reversed second half
My interviewer at Meta specifically said "You can modify the list." That's your hint to use this approach.
Approach 2: Using a Stack
Push first half onto a stack, then compare with second half as you pop. Simpler to implement but uses O(n) extra space. If interviewer says "optimize space," this won't fly.
Approach 3: Recursive (Elegant but Risky)
Use recursion to compare outer nodes working inward. Looks cool on paper but uses O(n) call stack space. I wouldn't use this in an interview unless you have time to kill.
Time Complexity
- Reverse approach: O(n) time, O(1) space - this is what they want
- Stack approach: O(n) time, O(n) space
- Recursive: O(n) time, O(n) space (call stack)
Pro tip: Start by asking "Can I modify the original list?" This tells you which approach to use.