Tensorum
LeetCode 234 · Palindrome

Palindrome Linked List

LeetCode 234 · Easy · solution, intuition & step-by-step walkthrough

Middle → reverse second half → compare.

EasyLinked ListTwo PointersStackRecursion
5 msruntime · beats 70%
77.5 MBmemory · beats 69%
1approach
7accepted runs · last 11 Dec 2024

This is how I solved Palindrome Linked List (LeetCode 234), an easy problem from the Palindrome pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Find the middle with slow/fast pointers, reverse the second half, and compare it against the first half node by node. Reverse it back afterwards to leave the list unchanged.

Approach

  1. 1

    Slow/fast to find the middle.

  2. 2

    Reverse from slow to the end.

  3. 3

    Walk both halves comparing values.

  4. 4

    Reverse the second half back.

How I solved it

Reverse second halfPythonO(n) time · O(1) space
class Solution:
    def reverseList(self, temp):
        prev = None
        while temp is not None:
            front = temp.next
            temp.next = prev
            prev = temp
            temp = front
        return prev

    def isPalindrome(self, head):
        if head is None:
            return False
        slow = head
        fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        p1 = head
        slow = self.reverseList(slow)
        p2 = slow
        is_palindrome = True
        while p1 is not None and p2 is not None:
            if p1.val != p2.val:
                is_palindrome = False
            p1 = p1.next
            p2 = p2.next
        slow = self.reverseList(slow)
        return is_palindrome
Loading the step-through…

Palindrome Linked List — FAQ

What is the intuition behind Palindrome Linked List?

Find the middle with slow/fast pointers, reverse the second half, and compare it against the first half node by node. Reverse it back afterwards to leave the list unchanged.

How do you solve Palindrome Linked List (LeetCode 234)?

1. Slow/fast to find the middle. 2. Reverse from slow to the end. 3. Walk both halves comparing values. 4. Reverse the second half back.

What is the time and space complexity of Palindrome Linked List?

Time: O(n). Space: O(1). (Accepted approach: Reverse second half.)

What are common mistakes in Palindrome Linked List?

Restoring the list is good practice — callers may reuse it.