Introduction
Palindrome Linked List means checking whether linked list reads the same forward and backward.
The task is to:
- find middle node
- reverse second half
- compare both halves
Example:
Input:1 -> 2 -> 2 -> 1
Output:
True
Explanation:
Forward:1 2 2 1
Backward:
1 2 2 1
Both are same. So linked list is palindrome.
This problem is one of the most important applications of:
Fast and Slow Pointer Technique Constraints
1 <= Number of Nodes <= 10^5-10^9 <= Node Value <= 10^9Approach 1 : Brute Force (Using Array)
Explanations:
Explanation:
The idea is:
- store linked list values in array
- compare from both ends
- check palindrome
Steps:
- Traverse linked list.
- Store values in array.
- Compare left and right.
- Return result.
This approach works but:
- uses extra memory
So in-place reversal is preferred.
Dry Run
Input:1 -> 2 -> 2 -> 1
Array:
[1,2,2,1]
Compare:
1 == 1
2 == 2
Palindrome exists
Practice :
Complexity Analysis :
Time Complexity:- O(n)Explanation :
Each node is visited once.
Space Complexity:- O(n)
Explanation :
Extra array is used.
Approach 2 : Optimal Solution(Using Fast & Slow Pointer)
Explanations:
Explanation:
This is the most optimized and interview-preferred solution.
The idea is:
- find middle node
- reverse second half
- compare both halves
This avoids extra memory usage.
Dry Run
Input:1 -> 2 -> 2 -> 1
Middle:
2
Reverse second half:
1 -> 2
Compare:
1 == 1
2 == 2
Palindrome exists
Practice :