Palindrome Linked List - Problem

Given the head of a singly linked list, determine if it represents a palindrome.

A palindrome reads the same forward and backward. For example, "racecar" or "madam" are palindromes. Your task is to check if the sequence of values in the linked list forms a palindrome when read from head to tail.

Goal: Return true if the linked list is a palindrome, false otherwise.

Challenge: Can you solve this in O(n) time and O(1) space?

Input & Output

example_1.py โ€” Simple Palindrome
$ Input: head = [1,2,2,1]
โ€บ Output: true
๐Ÿ’ก Note: The list reads as 1โ†’2โ†’2โ†’1, which is the same forwards and backwards, making it a palindrome.
example_2.py โ€” Not a Palindrome
$ Input: head = [1,2]
โ€บ Output: false
๐Ÿ’ก Note: The list reads as 1โ†’2, which is not the same when reversed (2โ†’1), so it's not a palindrome.
example_3.py โ€” Single Node
$ Input: head = [1]
โ€บ Output: true
๐Ÿ’ก Note: A single node is always considered a palindrome since it reads the same forwards and backwards.

Visualization

Tap to expand
Palindrome Detection: The Mirror TechniqueOriginal List: 1 โ†’ 2 โ†’ 3 โ†’ 2 โ†’ 1Step 1: Find Middle Point12321MiddleStep 2: Reverse Second Half12312Reversed!Step 3: Compare Both HalvesFirst Half1 โ†’ 2Reversed Half1 โ†’ 2Compareโœ“ Perfect Match - It's a Palindrome!Time: O(n) | Space: O(1)
Understanding the Visualization
1
The Two-Speed Race
Use a tortoise and hare approach: slow pointer moves one step, fast pointer moves two steps. When fast reaches the end, slow is at the middle.
2
The Great Reversal
Reverse the second half of the list, turning it into a mirror image that we can compare with the first half.
3
The Mirror Test
Compare nodes from the first half with the reversed second half, one by one, to check if they match perfectly.
Key Takeaway
๐ŸŽฏ Key Insight: By finding the middle and reversing half the list, we transform the palindrome check into a simple comparison between two forward-moving pointers, achieving optimal space complexity!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

We traverse the list a few times but each traversal is O(n), so overall O(n)

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

We only use a constant amount of extra space for pointers

n
2n
โœ“ Linear Space

Constraints

  • The number of nodes in the list is in the range [1, 105]
  • 0 โ‰ค Node.val โ‰ค 9
  • Follow-up: Could you do it in O(n) time and O(1) space?
Asked in
Amazon 45 Microsoft 38 Google 32 Meta 28 Apple 22
62.4K 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