EasyNo. 0234
Palindrome Linked List — LeetCode 234 Python Solution
- Pattern
- Linked List
- Topics
- Stack, Recursion, Linked List, Two Pointers
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given the head of a singly linked list, return true if it is a palindrome or false otherwise.
Example
- Input
- head = [1,2,2,1]
- Output
- true
Python solution
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
slow, fast = head, head.next
while fast and fast.next:
slow, fast = slow.next, fast.next.next
pre, cur = None, slow.next
while cur:
t = cur.next
cur.next = pre
pre, cur = cur, t
while pre:
if pre.val != head.val:
return False
pre, head = pre.next, head.next
return TrueComplexity
- Time
- O(n)where n is the length of the linked list
- Space · auxiliary
- O(1)
Pattern: Linked List
Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 234. Palindrome Linked List is filed here because LeetCode tags it Linked List, which is the vocabulary this hub collects.
The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0143 | Reorder List | Medium |
| 2130 | Maximum Twin Sum of a Linked List | Medium |
| 0224 | Basic Calculator | Hard |
| 0042 | Trapping Rain Water | Hard |
| 0114 | Flatten Binary Tree to Linked List | Medium |
| 0321 | Create Maximum Number | Hard |
Frequently asked questions
- How hard is LeetCode 234. Palindrome Linked List?
LeetCode 234. Palindrome Linked List is rated Easy on LeetCode.
- What is the time complexity of LeetCode 234. Palindrome Linked List?
The Python solution on this page runs in O(n), where n is the length of the linked list.
- What is the space complexity of LeetCode 234. Palindrome Linked List?
The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 234. Palindrome Linked List cover?
LeetCode 234. Palindrome Linked List is tagged Stack, Recursion, Linked List and Two Pointers on LeetCode.