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^50 <= values[i] <= 9- Linked-list verification time bound:
O(n) - Linked-list verification extra space bound:
O(1)
Step-by-step walkthrough
Understand the goal, the space rule, and the judge wrapper
Given a singly linked list, we want to return
Trueif its node values read the same forward and backward (for example,5 -> 9 -> 2 -> 9 -> 5), andFalseotherwise. Both an empty list and a single-node list count as palindromes.Two engineering rules make this problem interesting:
- Performance:
O(n)time andO(1)auxiliary space (meaning a fixed handful of pointer variables regardless of how long the list is). - Clean restoration: We are allowed to redirect
.nextpointers 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]tois_palindrome(values). We will build a realListNodechain fromvaluesinbuild_linked_list(input setup) and solve the actual linked-list problem insideis_palindrome_linked(head)usingO(1)extra space.- Performance:
Why copying values uses too much space
If this were an array, we would place one pointer at index
0and another atn - 1and walk them toward the middle. On a singly linked list,.nextarrows 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 fromheadto thek-th node from the end usesO(1)memory, but takesO(n^2)time.The key insight is: if we find the middle of the list and reverse the
.nextarrows of the second half in place, both halves now point toward the center, so we can walk inward from both ends inO(n)time andO(1)space—and then flip the second half back when we finish!Phase 1: find the end of the first half with slow and fast pointers
Use two pointers starting at
head:slowmoves 1 node per step andfastmoves 2 nodes per step. By loopingwhile fast.next is not None and fast.next.next is not None:,slowalways 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.nextis always the exact start of the second half (n // 2nodes), 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.nextPhase 2: reverse a linked list in place with three pointers
To reverse a chain of nodes without allocating memory, walk forward with
prev_node(initiallyNone) andcurr_node(initiallyhead). At each node, savenext_node = curr_node.nextbefore flippingcurr_node.next = prev_nodeso 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 currWhen
curr_nodereachesNone,prev_nodesits 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_nodePhase 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(fromhead) andright(fromreversed_second) togetherwhile right is not None:. Becauserighthasn // 2nodes andlefthas(n + 1) // 2nodes,rightalways hitsNonefirst (stopping right before the middle node whennis odd).Crucial detail: if
left.val != right.val, recordis_match = Falseandbreak—do notreturn Falseimmediately! That way Phase 4 always runs, reversingreversed_seconda second time and reconnectingslow.nextso 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_matchConnect `ListNode` to the judge signature
Finally, define
ListNode, writebuild_linked_listby iterating overreversed(values)to prepend each node inO(n)time, and wire upis_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)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 TrueComplete 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 takesn // 2iterations, reversing the second half takesn // 2steps, comparing both halves takes at mostn // 2steps, and reversing the second half back takesn // 2steps—roughly2npointer operations in total. - Space:
O(1)auxiliary space insideis_palindrome_linked. Only a fixed set of pointer variables (slow,fast,prev_node,curr_node,next_node,left,right) is used regardless ofn. (build_linked_listallocatesnnodes solely to convert the judge's PythonList[int]input into aListNodechain.)
Edge cases
- Empty list (
[]/head is None) and single node ([7]): Handled immediately at the top by returningTruebefore dereferencingfast.next. - Two nodes (
[4, 4]vs[4, 9]):fast.next.nextisNonebefore the first loop iteration, soslowstays on node0andslow.nextcleanly isolates node1as the second half. - Odd length (
[4, 0, 4]vs[4, 0, 5]):slowstops on the center node (0);righthas1node whilelefthas2, so the loop compares4against4(or5) and stops before reaching the unpaired center node. - Repeated rather than mirrored halves (
[1, 2, 1, 2]): Reversing the second half turns[1, 2]into2 -> 1, immediately catching1 != 2on 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 returningFalse. - Large lists (
10^5nodes): Purely iterative loops avoid stack overflow completely.
Common mistakes
- Returning
Falseimmediately on a mismatch instead ofbreaking. 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 landsslowone node further right on even-length lists; if you still reverseslow.next, you skip a middle node and falsely report[4, 9]asTrue! Always pairslow.nextreversal withwhile fast.next and fast.next.next:. - Overwriting
curr_node.nextbefore savingnext_node = curr_node.next. Oncecurr_node.next = prev_nodeexecutes, the forward link to the rest of the list is gone unless saved first. - Looping
while left is not None:instead ofwhile right is not None:. On odd-length lists,lefthas one extra node (the center), sorightbecomesNoneone step earlier andright.valwould raiseAttributeError.
Alternative approaches
- Copy values to an array (
vals == vals[::-1]): TakesO(n)time andO(n)auxiliary space without mutating pointers. Great to mention first in an interview as a baseline before optimizing space toO(1). - Reverse the first half while advancing
slowandfast: Fuses Phases 1 and 2 into a single pass, savingn // 2pointer 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
headmid-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 tradeO(n)extra space (copying values into a thread-local buffer) so zero.nextlinks 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 helpervisit(node)that descends untilnode is None, then comparesnode.val == front[0].valand advancesfront[0] = front[0].nextwhile unwinding from tail back to head. That leaves every.nextpointer untouched and runs inO(n)time, but consumesO(n)auxiliary call-stack space (nactive stack frames, which also exceeds Python's default recursion depth on10^5nodes). - 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
.nextand.prevreferences), neither midpoint finding nor pointer reversal is necessary. Locatetailin one forward pass (if not already stored on the list wrapper), then stepleftforward fromheadvialeft.nextandrightbackward fromtailviaright.prev, checkingleft.val == right.valuntil the pointers meet (left is right) or cross (left.prev is right), achievingO(n)time,O(1)space, and zero mutation.
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?
- How could you test symmetry using recursion alone without mutating any node pointers, and how much extra memory would that require?
- Suppose every node also stores a backward pointer to its predecessor—how does the algorithm simplify?
Similar questions
- Two-Thread Odd-Even Sequence Coordinator
- Locate a Celebrity Using an Acquaintance Matrix
- Maximum Contiguous Subarray Sum
- Collapse Adjacent Duplicate Letters
- System Architecture Walkthrough and Your Toughest Design Trade-Off
- Navigating Two High-Stakes Commitments on Colliding Timelines
More Omnissa interview questions
- Locate a Celebrity Using an Acquaintance Matrix Medium
- Maximum Contiguous Subarray Sum Medium
- System Architecture Walkthrough and Your Toughest Design Trade-Off Medium Pro
- Navigating Two High-Stakes Commitments on Colliding Timelines Medium Pro
- Two-Thread Odd-Even Sequence Coordinator Medium Pro
- Collapse Adjacent Duplicate Letters Medium Pro