Palindrome Linked List - Problem

Given the head of a singly linked list, return true if it is a palindrome or false otherwise.

A palindrome is a sequence that reads the same forward and backward.

Example: The linked list 1 → 2 → 2 → 1 is a palindrome because it reads the same forwards and backwards.

Input & Output

Example 1 — Basic Palindrome
$ Input: head = [1,2,2,1]
Output: true
💡 Note: The linked list reads the same forwards (1→2→2→1) and backwards (1→2→2→1), so it's a palindrome.
Example 2 — Not a Palindrome
$ Input: head = [1,2]
Output: false
💡 Note: The linked list reads 1→2 forwards but 2→1 backwards, which are different, so it's not a palindrome.
Example 3 — Single Node
$ Input: head = [1]
Output: true
💡 Note: A single node is always a palindrome since it reads the same forwards and backwards.

Constraints

  • The number of nodes in the list is in the range [1, 105]
  • 0 ≤ Node.val ≤ 9

Visualization

Tap to expand
Palindrome Linked List INPUT Singly Linked List: 1 2 2 1 NULL Input: head = [1, 2, 2, 1] Length: 4 nodes Type: Even length list Forward: 1 --> 2 --> 2 --> 1 Backward: 1 --> 2 --> 2 --> 1 ALGORITHM STEPS 1 Find Middle Use slow/fast pointers slow: 1 step, fast: 2 steps 1 2 2 1 mid=2 2 Reverse Second Half Reverse from middle to end Before: 2 --> 1 --> NULL After: 1 --> 2 --> NULL 3 Compare Both Halves Check values match First: 1,2 Second: 1,2 Match: OK 4 Return Result All matched = true Time: O(n) | Space: O(1) FINAL RESULT Palindrome Verification: First Half 1 2 Second Half (Reversed) 1 2 = = Output: true The list IS a palindrome [1,2,2,1] reads same forward and backward OK Key Insight: The optimal O(1) space solution uses the fast/slow pointer technique to find the middle, then reverses the second half in-place. By comparing the first half with the reversed second half, we can verify palindrome property without using extra space for storing values. TutorialsPoint - Palindrome Linked List | Optimal Solution (Reverse Second Half)
Asked in
Facebook 45 Amazon 38 Microsoft 32 Google 28
78.3K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen