Palindrome Check on a Singly Linked List

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

You are given an integer array values representing the node values of a singly linked list from front to back, where each node follows:

class ListNode:
    def __init__(self, val: int = 0, next: Optional["ListNode"] = None):
        self.val = val
        self.next = next

Implement is_palindrome(values: List[int]) -> bool by constructing the singly linked list of ListNode objects and checking whether its node values form a palindrome—that is, the front-to-back order matches the back-to-front order. An empty list and a single-node list both count as palindromes.

Your linked-list check must run in O(n) time and O(1) extra working memory beyond the n list nodes themselves. Temporary in-place adjustments to .next links are allowed during traversal, provided all links are restored to their original forward order before returning.

Examples

Example 1

Input: values = [8, 3, 3, 8]
Output: True

Walking from head to tail yields 8 -> 3 -> 3 -> 8, which matches the reverse order 8, 3, 3, 8.

Example 2

Input: values = [5, 9, 2, 9, 5]
Output: True

The left pair [5, 9] mirrors the right pair [9, 5] across the central node 2.

Example 3

Input: values = [6, 4, 7, 6]
Output: False

Although both outer endpoints hold 6, the two middle positions disagree (4 != 7), so the linked list is not symmetric.

Constraints

  • 0 <= len(values) <= 10^5
  • 0 <= values[i] <= 9
  • Linked-list verification time bound: O(n)
  • Linked-list verification extra space bound: O(1)

Step-by-step walkthrough

  1. Understand the goal, the space rule, and the judge wrapper

    Given a singly linked list, we want to return True if its node values read the same forward and backward (for example, 5 -> 9 -> 2 -> 9 -> 5), and False otherwise. Both an empty list and a single-node list count as palindromes.

    Two engineering rules make this problem interesting:

    • Performance: O(n) time and O(1) auxiliary space (meaning a fixed handful of pointer variables regardless of how long the list is).
    • Clean restoration: We are allowed to redirect .next pointers temporarily, and we should put every pointer back in its original order before returning.

    Note on the judge signature: the automated test runner passes values: List[int] to is_palindrome(values). We will build a real ListNode chain from values in build_linked_list (input setup) and solve the actual linked-list problem inside is_palindrome_linked(head) using O(1) extra space.

  2. Why copying values uses too much space

    If this were an array, we would place one pointer at index 0 and another at n - 1 and walk them toward the middle. On a singly linked list, .next arrows only point forward—there is no way to step backward from the tail!

    Copying the node values into a Python list or stack lets us read backward, but costs O(n) extra memory. Repeatedly walking from head to the k-th node from the end uses O(1) memory, but takes O(n^2) time.

    The key insight is: if we find the middle of the list and reverse the .next arrows of the second half in place, both halves now point toward the center, so we can walk inward from both ends in O(n) time and O(1) space—and then flip the second half back when we finish!

  3. Phase 1: find the end of the first half with slow and fast pointers

    Use two pointers starting at head: slow moves 1 node per step and fast moves 2 nodes per step. By looping while fast.next is not None and fast.next.next is not None:, slow always stops on the last node of the first half:

    Even length (n = 4):   8  ->  3  ->  3  ->  8  -> None
      start:              s,f
      after 1 step:               s             f     (f.next.next is None -> stop!)
      split after s:      [8 -> 3]   and   [3 -> 8]   (2 nodes vs 2 nodes)
    
    Odd length (n = 5):    5  ->  9  ->  2  ->  9  ->  5  -> None
      start:              s,f
      after 1 step:               s             f
      after 2 steps:                     s             f   (f.next is None -> stop!)
      split after s:      [5 -> 9 -> 2]  and  [9 -> 5]     (middle node 2 stays on the left)
    

    Notice how convenient this stopping rule is: slow.next is always the exact start of the second half (n // 2 nodes), and for odd lengths the unpaired middle node sits harmlessly at the end of the first half.

        # An empty list or single-node list reads the same both ways.
        if head is None or head.next is None:
            return True
    
        # Phase 1: move slow by 1 step and fast by 2 steps.
        slow: ListNode = head
        fast: ListNode = head
        while fast.next is not None and fast.next.next is not None:
            slow = slow.next
            fast = fast.next.next
    
  4. Phase 2: reverse a linked list in place with three pointers

    To reverse a chain of nodes without allocating memory, walk forward with prev_node (initially None) and curr_node (initially head). At each node, save next_node = curr_node.next before flipping curr_node.next = prev_node so you do not lose the rest of the chain:

    Before step:    None <- [A]     [B] -> [C] -> None
                            prev    curr   next
    
    Flip arrow:     None <- [A] <-- [B]    [C] -> None
    Advance both:                   prev   curr
    

    When curr_node reaches None, prev_node sits on the old tail—which is the new head of the reversed list!

    def reverse_list(head: Optional[ListNode]) -> Optional[ListNode]:
        # prev_node: head of the already-reversed prefix (starts empty at None).
        # curr_node: next node in the remaining forward chain still to be flipped.
        prev_node: Optional[ListNode] = None
        curr_node: Optional[ListNode] = head
        while curr_node is not None:
            # Save curr_node.next BEFORE overwriting it, otherwise the rest of the list is lost.
            next_node = curr_node.next
            curr_node.next = prev_node
            prev_node = curr_node
            curr_node = next_node
        return prev_node
    
  5. Phase 3 & Phase 4: compare both halves, then restore the list

    Detach the second half cleanly (second_half_start = slow.next; slow.next = None) and reverse it (reversed_second = reverse_list(second_half_start)).

    Now advance left (from head) and right (from reversed_second) together while right is not None:. Because right has n // 2 nodes and left has (n + 1) // 2 nodes, right always hits None first (stopping right before the middle node when n is odd).

    Crucial detail: if left.val != right.val, record is_match = False and break—do not return False immediately! That way Phase 4 always runs, reversing reversed_second a second time and reconnecting slow.next so the caller's list is left completely intact.

        # Phase 2: detach the second half (length n // 2) and reverse its pointers in place.
        second_half_start = slow.next
        slow.next = None
        reversed_second = reverse_list(second_half_start)
    
        # Phase 3: compare from the front and from the reversed tail inward.
        left: Optional[ListNode] = head
        right: Optional[ListNode] = reversed_second
        is_match = True
        while right is not None:
            if left.val != right.val:
                # Break instead of returning early so Phase 4 still restores the caller's list.
                is_match = False
                break
            left = left.next
            right = right.next
    
        # Phase 4: reverse the second half back to its original order and reconnect slow.next.
        slow.next = reverse_list(reversed_second)
        return is_match
    
  6. Connect `ListNode` to the judge signature

    Finally, define ListNode, write build_linked_list by iterating over reversed(values) to prepend each node in O(n) time, and wire up is_palindrome(values).

    class ListNode:
        def __init__(self, val: int = 0, next: Optional["ListNode"] = None):
            self.val = val
            self.next = next
    
    
    def build_linked_list(values: List[int]) -> Optional[ListNode]:
        # Build from back to front so each new ListNode points to the suffix built so far.
        head: Optional[ListNode] = None
        for value in reversed(values):
            head = ListNode(value, head)
        return head
    
    
    def is_palindrome(values: List[int]) -> bool:
        # Convert the judge's Python list into ListNode objects, then run the O(1)-space check.
        head = build_linked_list(values)
        return is_palindrome_linked(head)
    
  7. Full pointer trace on Example 2 (`[5, 9, 2, 9, 5]`)

    Start:
      5 -> 9 -> 2 -> 9 -> 5 -> None
    
    Phase 1 (find end of first half):
      slow stops at 2, fast stops at last 5.
    
    Phase 2 (detach after 2 and reverse second half):
      first half:       5 -> 9 -> 2 -> None
      reversed_second:  5 -> 9 -> None
    
    Phase 3 (walk left and right together):
      step 1: left = 5, right = 5  (match) -> advance both
      step 2: left = 9, right = 9  (match) -> advance both
      step 3: left = 2, right = None       -> loop ends, is_match = True
    
    Phase 4 (reverse second half back and reconnect to 2.next):
      restored: 5 -> 9 -> 2 -> 9 -> 5 -> None
      return True
    
  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    class ListNode:
        def __init__(self, val: int = 0, next: Optional["ListNode"] = None):
            self.val = val
            self.next = next
    
    
    def build_linked_list(values: List[int]) -> Optional[ListNode]:
        # Build from back to front so each new ListNode points to the suffix built so far.
        head: Optional[ListNode] = None
        for value in reversed(values):
            head = ListNode(value, head)
        return head
    
    
    def reverse_list(head: Optional[ListNode]) -> Optional[ListNode]:
        # prev_node: head of the already-reversed prefix (starts empty at None).
        # curr_node: next node in the remaining forward chain still to be flipped.
        prev_node: Optional[ListNode] = None
        curr_node: Optional[ListNode] = head
        while curr_node is not None:
            # Save curr_node.next BEFORE overwriting it, otherwise the rest of the list is lost.
            next_node = curr_node.next
            curr_node.next = prev_node
            prev_node = curr_node
            curr_node = next_node
        return prev_node
    
    
    def is_palindrome_linked(head: Optional[ListNode]) -> bool:
        # An empty list or single-node list reads the same both ways.
        if head is None or head.next is None:
            return True
    
        # Phase 1: move slow by 1 step and fast by 2 steps.
        # Checking fast.next and fast.next.next stops slow on the LAST node of the first half
        # (index (n - 1) // 2: left-middle for even n, exact center node for odd n).
        slow: ListNode = head
        fast: ListNode = head
        while fast.next is not None and fast.next.next is not None:
            slow = slow.next
            fast = fast.next.next
    
        # Phase 2: detach the second half (length n // 2) and reverse its pointers in place.
        second_half_start = slow.next
        slow.next = None
        reversed_second = reverse_list(second_half_start)
    
        # Phase 3: compare from the front and from the reversed tail inward.
        # Because len(reversed_second) == n // 2 <= len(first_half), right reaches None first,
        # leaving an odd-length list's middle node safely unpaired at the end of first_half.
        left: Optional[ListNode] = head
        right: Optional[ListNode] = reversed_second
        is_match = True
        while right is not None:
            if left.val != right.val:
                # Break instead of returning early so Phase 4 still restores the caller's list.
                is_match = False
                break
            left = left.next
            right = right.next
    
        # Phase 4: reverse the second half back to its original order and reconnect slow.next.
        slow.next = reverse_list(reversed_second)
        return is_match
    
    
    def is_palindrome(values: List[int]) -> bool:
        # Convert the judge's Python list into ListNode objects, then run the O(1)-space check.
        head = build_linked_list(values)
        return is_palindrome_linked(head)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine checking whether a long row of one-way stepping stones has symmetric colors without writing the colors down on paper. Because each stone only points forward to the next stone, you cannot step backward from the far end—unless you walk two scouts (one moving two stones per turn and one moving one stone per turn) to locate the halfway stone, temporarily turn the arrows on the second half around so they point inward, walk from both ends comparing colors step by step, and flip the arrows back when finished. This combines fast-and-slow pointers (two references advancing at 2x and 1x speed to locate a list's midpoint in one pass) with in-place reversal (redirecting existing .next pointers without allocating new nodes) to use O(1) auxiliary space (extra working memory beyond the input list itself).

The obvious approach—copying every node's value into an array or stack and comparing with its reverse—is easy to write, but allocates O(n) extra memory and violates the O(1) space rule. Avoiding extra memory by repeatedly walking from head to the (n - 1 - i)-th node for each index i takes O(n^2) time, which requires roughly 5 * 10^9 steps on 10^5 nodes. Using recursion to reach the tail and compare while unwinding the call stack also fails the O(1) space bound because n active stack frames consume O(n) memory (and crash Python's default 1,000-frame recursion limit).

Here is how our four-phase pointer dance checks 5 -> 9 -> 2 -> 9 -> 5:

1. Midpoint:  slow stops on 2 (end of first half)
2. Reverse:   first = [5 -> 9 -> 2 -> None],  second = [5 -> 9 -> None]
3. Compare:   (5 == 5), (9 == 9), second hits None -> is_match = True
4. Restore:   reverse second back to [9 -> 5 -> None], attach after 2 -> 5 -> 9 -> 2 -> 9 -> 5

Complexity

Let n be the number of nodes in the linked list.

  • Time: O(n). Finding the midpoint takes n // 2 iterations, reversing the second half takes n // 2 steps, comparing both halves takes at most n // 2 steps, and reversing the second half back takes n // 2 steps—roughly 2n pointer operations in total.
  • Space: O(1) auxiliary space inside is_palindrome_linked. Only a fixed set of pointer variables (slow, fast, prev_node, curr_node, next_node, left, right) is used regardless of n. (build_linked_list allocates n nodes solely to convert the judge's Python List[int] input into a ListNode chain.)

Edge cases

  • Empty list ([] / head is None) and single node ([7]): Handled immediately at the top by returning True before dereferencing fast.next.
  • Two nodes ([4, 4] vs [4, 9]): fast.next.next is None before the first loop iteration, so slow stays on node 0 and slow.next cleanly isolates node 1 as the second half.
  • Odd length ([4, 0, 4] vs [4, 0, 5]): slow stops on the center node (0); right has 1 node while left has 2, so the loop compares 4 against 4 (or 5) and stops before reaching the unpaired center node.
  • Repeated rather than mirrored halves ([1, 2, 1, 2]): Reversing the second half turns [1, 2] into 2 -> 1, immediately catching 1 != 2 on the first comparison.
  • Mismatch right next to the center ([3, 1, 4, 5, 1, 3]): Fails on the final step (4 != 5), then still executes Phase 4 to restore the list before returning False.
  • Large lists (10^5 nodes): Purely iterative loops avoid stack overflow completely.

Common mistakes

  • Returning False immediately on a mismatch instead of breaking. Skipping Phase 4 leaves the caller's list severed in half with its second half reversed.
  • Off-by-one midpoint condition (while fast and fast.next:). That loop lands slow one node further right on even-length lists; if you still reverse slow.next, you skip a middle node and falsely report [4, 9] as True! Always pair slow.next reversal with while fast.next and fast.next.next:.
  • Overwriting curr_node.next before saving next_node = curr_node.next. Once curr_node.next = prev_node executes, the forward link to the rest of the list is gone unless saved first.
  • Looping while left is not None: instead of while right is not None:. On odd-length lists, left has one extra node (the center), so right becomes None one step earlier and right.val would raise AttributeError.

Alternative approaches

  • Copy values to an array (vals == vals[::-1]): Takes O(n) time and O(n) auxiliary space without mutating pointers. Great to mention first in an interview as a baseline before optimizing space to O(1).
  • Reverse the first half while advancing slow and fast: Fuses Phases 1 and 2 into a single pass, saving n // 2 pointer steps, but requires slightly more delicate odd-vs-even bookkeeping to skip the center node and restore the first half afterward.

Follow-up questions

  • If other threads might traverse the list at the same time, how can you check for a palindrome safely without exposing broken links? In-place pointer reversal temporarily severs the list at the midpoint and reverses the back half, so an unsynchronized reader walking from head mid-operation would see a truncated list! To keep in-place reversal safe, acquire an exclusive write guard on a readers-writer lock (a synchronization primitive permitting many simultaneous readers or one exclusive writer) across all four phases so readers wait until restoration finishes. If readers cannot be blocked, hold a shared read guard instead and trade O(n) extra space (copying values into a thread-local buffer) so zero .next links are mutated.
  • How could you test symmetry using recursion alone without mutating any node pointers, and how much extra memory would that require? Store a mutable front cursor front = [head] outside a recursive helper visit(node) that descends until node is None, then compares node.val == front[0].val and advances front[0] = front[0].next while unwinding from tail back to head. That leaves every .next pointer untouched and runs in O(n) time, but consumes O(n) auxiliary call-stack space (n active stack frames, which also exceeds Python's default recursion depth on 10^5 nodes).
  • Suppose every node also stores a backward pointer to its predecessor—how does the algorithm simplify? On a doubly linked list (where each node maintains both .next and .prev references), neither midpoint finding nor pointer reversal is necessary. Locate tail in one forward pass (if not already stored on the list wrapper), then step left forward from head via left.next and right backward from tail via right.prev, checking left.val == right.val until the pointers meet (left is right) or cross (left.prev is right), achieving O(n) time, O(1) space, and zero mutation.

Follow-up questions

Similar questions

More Omnissa interview questions

All 7 Omnissa questions →