Task example: Palindrome Linked List

Check whether the values in a singly linked list read the same forward and backward. Return True if they do, otherwise False.

Example 1
Input
head = [1,2,2,1]
Output
True

Compare node values, not node identities. Both solutions below preserve the original list. A single node is a palindrome.

LeetCode 234 ↗
01 / Values list (extra space)

Values list: video explanation

head = [1,2,2,1]
result = True

Prefer reading? Follow the steps below.

  1. Follow next from head to the end, appending each node value to values.
  2. Create the reversed copy with values[::-1]. For [1,2,2,1], both sequences are [1,2,2,1].
  3. Return whether the sequences match. For [1,2], the reversed copy is [2,1], so the result is False.

Time complexity · O(N)

Visit N nodes, reverse N values, and compare at most N positions. These linear passes add up to O(N).

Space complexity · O(N)

The collected values and their reversed copy require O(N) extra space.

PYTHONLive code trace
02 / Reverse second half (optimal space)

Reverse second half: video explanation

head = [1,2,2,1]
result = True

Prefer reading? Follow the steps below.

  1. Move slow one link and fast two links while fast can move twice. Slow stops at the end of the first half, or at the center for an odd length.
  2. Reverse the nodes after slow. Compare from head and the reversed half, moving both references forward. Stop on a mismatch or when the right half ends.
  3. Reverse the second half again and reconnect it through slow.next before returning result. This restores the input even after a mismatch.

Both approaches take linear time. Reversing the second half avoids an extra values list, reducing extra space from O(N) to O(1).

Time complexity · O(N)

Finding the midpoint, two reversals, and comparisons do O(N) total work.

Space complexity · O(1)

A fixed number of references is enough. The reverse helper is iterative, so it does not use a growing recursion stack.

PYTHONLive code trace

Palindrome Linked List · The task

Close or press Esc to return to your place. The task button stays pinned while you explore the solutions.