#234
Palindrome Linked List
EasyLinked ListTwo PointersStackRecursionTwo PointersLinked List
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n) | O(1) |
💡
Intuition
Time O(n)Space O(1)
To check if a linked list is a palindrome efficiently, we can use the two-pointer technique to find the middle of the list and then reverse the second half to compare it with the first half.
⚙️
Algorithm
4 steps- 1Step 1: Use two pointers to find the middle of the linked list.
- 2Step 2: Reverse the second half of the linked list.
- 3Step 3: Compare the first half and the reversed second half node by node.
- 4Step 4: Restore the original list (optional) and return the result.
solution.py18 lines
1def isPalindrome(head):
2 slow = fast = head
3 while fast and fast.next:
4 slow = slow.next
5 fast = fast.next.next
6 prev = None
7 while slow:
8 next_node = slow.next
9 slow.next = prev
10 prev = slow
11 slow = next_node
12 left, right = head, prev
13 while right:
14 if left.val != right.val:
15 return False
16 left = left.next
17 right = right.next
18 return Trueℹ
Complexity note: The time complexity is O(n) because we traverse the list a constant number of times. The space complexity is O(1) since we only use a few pointers for traversal and comparison.
- 1Using two pointers helps find the middle efficiently.
- 2Reversing the second half allows direct comparison.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.