Python coding

List that reads the same backwards

Write is_palindrome(head): return True if the values of a singly linked list read the same front to back as back to front, like 1 → 2 → 2 → 1 or 3 → 7 → 3, and False otherwise. An empty list (head is None) and a single node both count as palindromes. Each ListNode has val and next.

Use O(n) time and O(1) extra memory: no list, stack or string of the values. You may re-link nodes while you check, but the list must be back as you found it when you return.

The tests call the provided run_is_palindrome(values), which builds the list from values, calls your function and checks that the list was restored.

Besides the tests, one large input (a 6,000-node list) with a ~95 ms limit (scaled to your device's speed): brute force won't pass.

  • run_is_palindrome([1,2,2,1]) → true
  • run_is_palindrome([3,7,3]) → true
  • run_is_palindrome([1,2,3,1]) → false
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Compose the classic routines: fast/slow pointers to find the middle, an in-place reversal of the second half, then one walk that compares both halves.

Hint 2

while fast and fast.next leaves slow on the first node of the second half. Reverse from slow and compare from both ends until the reversed half runs out.

Hint 3

Before returning, reverse that half again. The first half still points at slow, so reversing back reconnects the list exactly as it was.

Solution and why it works
pythonO(n) · O(1)
# --- your code ---
def reverse(head: "ListNode | None") -> "ListNode | None":
    prev = None
    while head is not None:
        nxt = head.next
        head.next = prev
        prev, head = head, nxt
    return prev


def is_palindrome(head: "ListNode | None") -> bool:
    slow = fast = head
    while fast is not None and fast.next is not None:
        slow, fast = slow.next, fast.next.next   # slow: first node of the second half
    back = reverse(slow)                         # the second half, read from the tail
    front, node = head, back
    while node is not None and node.val == front.val:
        front, node = front.next, node.next
    reverse(back)                                # restore the original links
    return node is None                          # reached the end: no mismatch


# --- provided: do not edit ---
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


def build_list(values: list[int]) -> ListNode | None:
    head = None
    for v in reversed(values):
        head = ListNode(v, head)
    return head


def to_nodes(head: ListNode | None, limit: int) -> list[ListNode]:
    out = []
    while head is not None:
        if len(out) == limit:
            raise ValueError("the list has more nodes than it started with: is there a cycle?")
        out.append(head)
        head = head.next
    return out


def run_is_palindrome(values: list[int]) -> bool:
    head = build_list(values)
    given = to_nodes(head, len(values))
    try:
        answer = is_palindrome(head)
        if to_nodes(head, len(values)) != given:
            raise ValueError("put the list back as you found it: same nodes, in the same order")
        return answer
    finally:
        for n in given:                  # free node by node: a long chain freed at once overflows Pyodide's stack
            n.next = None

A singly linked list can't be read backwards, so reverse its second half in place: fast/slow pointers find where it starts in one pass, and the reversal lets you walk it from the tail inwards. Compare the two halves node by node, then reverse that half again so the caller gets its list back. Every step is O(n) time and O(1) memory. Copying the values into a list is simpler but O(n) memory; walking from the head to each node's mirror is O(n²).