28/39
Part 6 of 7 · The worked exampleLearn

A worked example: does the list read the same both ways?

The prompt: given the head of a singly linked list, say whether its values read the same forwards and backwards, using O(1) extra memory. 3 -> 1 -> 4 -> 1 -> 3 does. 1 -> 2 -> 3 doesn't.

Clarify. Say out loud that the empty list and a single node count as reading the same. Then ask: can I change the list while I work? Say you will, and that you'll put it back before returning, because callers don't expect a read-only question to rearrange their data.

The obvious answer. Copy the values into a Python list and compare it with its reverse: vals == vals[::-1]. That's O(n) time and O(n) memory. Say it, then say why it doesn't meet the memory limit.

The insight. Reading backwards is what a singly linked list can't do. So reverse the second half in place, compare it with the first half, and reverse it back. That needs three pieces you've built: two speeds to find the middle, the in-place reverse, and pointer care to restore it.

def reads_same_both_ways(head):
    if head is None or head.next is None:
        return True
    # stop slow at the end of the first half
    slow = fast = head
    while fast.next is not None and fast.next.next is not None:
        slow, fast = slow.next, fast.next.next
    # reverse the second half in place
    second = reverse(slow.next)
    a, b, same = head, second, True
    while b is not None:
        if a.val != b.val:
            same = False
            break
        a, b = a.next, b.next
    # put it back
    slow.next = reverse(second)
    return same


print(reads_same_both_ways(linked([3, 1, 4, 1, 3])), reads_same_both_ways(linked([1, 2, 3])))
True False
Predict

On 3, 1, 4, 1, 3, slow stops at the end of the first half. Which node is that?

Pick an answer above to see the rest