Palindrome Linked List

Check whether the values of a singly linked list read the same from both ends, without copying them.

Given the head of a singly linked list, return true if its values read the same from the first node to the last as from the last node to the first, and false otherwise. As a further challenge, solve it in O(n) time, where n is the number of nodes, with only a fixed amount of extra memory, O(1) space.

Example 1
Input: head = [1, 2, 2, 1]
Output: true
Example 2
Input: head = [1, 2]
Output: false
Example 3
Input: head = [1, 2, 3, 2, 1]
Output: true
Solution

The Idea

You have probably met words like "level" or "racecar", which give the same letters whether you read them from the left or from the right. Words like these are called palindromes, and a list of numbers can be one too. Read 1, 2, 2, 1 from either end and you get 1, 2, 2, 1, which is why Example 1 returns true.

The numbers here sit in a singly linked list. Each value is kept in a node, and each node knows only the node after it, through its next link. Where the list ends, next is null. We are handed only the first node, the head, so we can walk forwards but never step back.

With an array, we would put one finger on the first value and one on the last, and move them toward each other, comparing as we go. In the list, the right-hand finger is stuck: the last 1 has no link back to the 2 before it. So how can we read the list from the end?

We do not have to. Only the second half needs to be read backwards, and we can turn its links around. Then the last node becomes the start of a short list that runs back toward the middle, and both halves can be walked forwards, side by side. Look at the picture below.

The list 1, 2, 2, 1. In the top row, slow stops on the second 2 while fast runs off the end to null. In the bottom row, the second half is reversed, so the last 1 points back at that 2, which now points to null. p starts at head and q at the reversed half, and they compare 1 with 1 and 2 with 2.

The top row, labelled "1. slow and fast find the middle", shows how to find where the second half starts. Two markers start at head: slow moves one node at a time and fast moves two. When fast runs off the end to null, slow has gone half as far and stands on the second 2.

The bottom row, labelled "2. after reversing the second half", shows the same nodes after the links from that 2 onwards are turned around. The last 1 now points back at the 2, and the 2 points to null. Marker p, labelled "p (from head)", starts at the head, and marker q, labelled "q (from end)", starts at the last 1. Both walk forwards: 1 matches 1, 2 matches 2, and then q reaches null.

So the list never has to be read backwards. It is enough to turn half of it around, compare two forward walks, and turn that half back.

Solution Approach

The simple way with an array shows what the reversal saves; after it, the code has four things to settle: finding the middle, reversing the second half, knowing when the comparison stops, and giving the list back unchanged.

The simple way with an array

Why not copy the values into an array and compare from both ends there? That works, and it takes O(n) time. But the array holds a copy of every value, so the extra memory grows with the list. Reversing half of the list in place needs only a few variables, whatever its length.

Finding the middle

How do we know where the second half starts, without knowing the length? We could count the nodes first and then walk half that far. The slow and fast markers do it in one walk, because fast covers twice the distance. The same idea has its own page, Middle of the Linked List.

For an odd length such as Example 3, [1, 2, 3, 2, 1], slow stops on the 3 in the centre. For an even length it stops on the first node of the second half, like the second 2 in the picture. Either way, the part from slow to the end has at most one node more than the part before it, and only when the length is odd.

Reversing the second half

How do we turn the links around? Walk the second half one node at a time and point each node's next at the node before it, remembering the old next first so the walk can go on. The last node visited becomes the start of the reversed half. Reverse Linked List covers this step in detail.

One link is left alone: the node just before slow still points at slow. In the picture, the first 2 still points at the second 2, so the walk from the head is 1, 2, 2, while the reversed half is only 1, 2.

When the comparison stops

Which walk decides when to stop? The reversed half, because it is never longer than the walk from the head. The comparison runs while q is not null. For [1, 2, 3, 2, 1], both walks end on the 3, so the 3 is compared with itself, which always matches and does no harm.

Giving the list back

Why put the list back? Whoever called the method only asked a question, and may still need the list afterwards. Reversing the reversed half again restores every link, and the node before the middle never lost its link, so the list is whole again. For this to run on a mismatch too, the answer is stored in a variable and the loop is left with break, instead of returning straight away.

Java Solution

The method isPalindrome works in these steps:

  1. First, find the middle. slow and fast both start at head. While fast and fast.next are not null, slow moves one node and fast moves two.
  2. Reverse the list from slow onwards with the helper reverse, and keep the start of the reversed half in second. Inside reverse, prev starts as null. For each node, it saves the following node in next, points the node at prev, and moves both one step on.
  3. Compare the halves. p starts at head, q at second, and same starts as true. While q is not null, compare their values: on a difference, set same to false and break out, otherwise move both on.
  4. Call reverse(second) again to put the links back, then return same.

The main method runs the three examples, [1, 2, 3, 1] (the ends match but the middle does not), a one-node list and an empty list. For each, it prints the list, the answer, and the list again after the call. ListNode is the node class, and the helpers build and show turn numbers into a list and a list into text.

Java
public class PalindromeLinkedList {

    static class ListNode {
        int val;
        ListNode next;
        ListNode(int val) { this.val = val; }
    }

    public static boolean isPalindrome(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {  // fast moves two nodes, slow one
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode second = reverse(slow);             // reverse the second half
        ListNode p = head;
        ListNode q = second;
        boolean same = true;
        while (q != null) {                          // the reversed half decides when to stop
            if (p.val != q.val) {
                same = false;
                break;
            }
            p = p.next;
            q = q.next;
        }
        reverse(second);                             // put the list back as it was
        return same;
    }

    private static ListNode reverse(ListNode head) {
        ListNode prev = null;
        while (head != null) {
            ListNode next = head.next;
            head.next = prev;                        // turn this link around
            prev = head;
            head = next;
        }
        return prev;
    }

    static ListNode build(int... values) {
        ListNode dummy = new ListNode(0);
        ListNode tail = dummy;
        for (int v : values) {
            tail.next = new ListNode(v);
            tail = tail.next;
        }
        return dummy.next;
    }

    static String show(ListNode head) {
        StringBuilder sb = new StringBuilder("[");
        for (ListNode n = head; n != null; n = n.next) {
            sb.append(n.val).append(n.next != null ? ", " : "");
        }
        return sb.append("]").toString();
    }

    static void check(int... values) {
        ListNode head = build(values);
        String before = show(head);
        boolean result = isPalindrome(head);
        System.out.println(before + " -> " + result + ", list afterwards: " + show(head));
    }

    public static void main(String[] args) {
        check(1, 2, 2, 1);
        check(1, 2);
        check(1, 2, 3, 2, 1);
        check(1, 2, 3, 1);
        check(7);
        check();
    }
}

Running it prints:

Output
[1, 2, 2, 1] -> true, list afterwards: [1, 2, 2, 1]
[1, 2] -> false, list afterwards: [1, 2]
[1, 2, 3, 2, 1] -> true, list afterwards: [1, 2, 3, 2, 1]
[1, 2, 3, 1] -> false, list afterwards: [1, 2, 3, 1]
[7] -> true, list afterwards: [7]
[] -> true, list afterwards: []

The answers true, false and true match the three examples, and every line ends with the list exactly as it went in. Look at the line for [1, 2, 3, 1]: the comparison met 2 against 3, set same to false and broke out, yet the second reverse still ran, so the list reads [1, 2, 3, 1] afterwards.

The last two lines are the smallest lists. For [7], slow never moves, so q starts on the same node as p and the 7 is compared with itself. For [], head is null, reverse(null) returns null, and the comparison loop never runs, so the answer stays true.

The loop condition on q matters. Changed to while (p != null), it follows the longer walk from the head, 1, 2, 2, and on [1, 2, 2, 1] the third step reads q.val after q has become null. Running that version throws a NullPointerException.

Complexity

The method walks the list a fixed number of times and keeps only a handful of node references.

  • Time: O(n). slow and fast cross the list once, each of the two reversals touches only the nodes from the middle on, and the comparison takes at most that many steps.
  • Space: O(1). The second half is turned around by changing the next links of the existing nodes, so no copy of the values is made, only a few variables such as slow, p, q and prev.