Palindrome Linked List — LeetCode 234 Python Solution
EasyStackRecursionLinked ListTwo Pointers
- Problem
- #234
- Pattern
- Linked List
- 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
Python
# 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
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the linked list |
| Space | O(1) auxiliary |
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
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.