Add Two Numbers

Add two numbers stored digit by digit in linked lists, ones digit first, the way you add on paper.

Two non-negative whole numbers are each stored in a linked list, one digit per node, with the ones digit in the first node. So 342 is stored as 2, then 4, then 3. Given the first nodes of the two lists, l1 and l2, add the two numbers and return the sum as a list in the same form.

Example 1
Input: l1 = [2, 4, 3], l2 = [5, 6, 4]
Output: [7, 0, 8]
Explanation: 342 + 465 = 807.
Example 2
Input: l1 = [9, 9, 9], l2 = [1]
Output: [0, 0, 0, 1]
Explanation: 999 + 1 = 1000, so the sum has one digit more than either number.
Solution

The Idea

To add 342 and 465 on paper, you write one number under the other and start on the right: the ones column, then the tens, then the hundreds. Each column gives one digit of the answer. When a column adds up to 10 or more, you write the last digit and pass the extra 1 to the next column. That extra 1 is called the carry.

Here the numbers come as linked lists. A linked list is a chain of small objects called nodes. Each node holds one value and a link, named next, to the following node. The last node's next is null, which means nothing follows. The first node is called the head, and every other node is reached by following the links from it.

In Example 1, l1 is 2, 4, 3, which is 342 written ones digit first, and l2 is 5, 6, 4, which is 465. So where should the addition start? On paper it starts at the ones digit, and in these lists the ones digit sits in the head, the one node we can reach right away. Look at the picture below.

The lists l1 = 2, 4, 3 and l2 = 5, 6, 4 lined up in a ones, tens and hundreds column. The ones column gives 7. The tens column gives 10, so the result gets 0 and a carry of 1 goes to the hundreds column, which gives 3 + 4 + 1 = 8. The result list is 7, 0, 8.

Each column in the picture holds one node of l1 above one node of l2. The ones column gives 2 + 5 = 7, the first node of the row labelled result. The tens column, in orange, gives 4 + 6 = 10, so the result gets 0, and the orange arrow takes the carry of 1 to the hundreds column. There, 3 + 4 + 1 = 8. Read from the last node back to the first, the result is 807.

So storing the ones digit first gives exactly the order column addition needs. Walking both lists from their heads, one node at a time, visits the columns just as on paper, and each step adds one node to the result.

Example 2 adds a twist. In 999 + 1, every column carries, and after the hundreds column both lists have ended while a carry of 1 is still waiting. On paper you would write that 1 in front, making 1000. The result list needs one more node than the longer input list.

Solution Approach

Turning that idea into code means first seeing why a plain conversion to a number falls short. Then four things need settling: lists of different lengths, a column's digit and carry, when to stop, and how to build the result list.

Converting the lists to numbers

Why not read each list into a Java long, add the two, and turn the sum back into a list? The largest long has 19 digits, and a list of 30 nodes holds a 30-digit number. Adding column by column, as on paper, works for any length, because it never needs the whole number at once.

Lists of different lengths

What if one list ends before the other? Take [1, 8] plus [0], which is 81 + 0. After the ones column, l2 has no nodes left, and on paper the empty space under the 8 counts as 0. The code does the same: it adds a node's value only while that list still has a node.

The digit and the carry of a column

How does a column's sum become a digit and a carry? Two digits and a carry add up to at most 9 + 9 + 1 = 19. The digit to write is sum % 10, the remainder after dividing by 10. The carry is sum / 10, which Java rounds down to a whole number: 1 for sums from 10 to 19, and 0 below 10. For the tens column in the picture, 10 % 10 is 0 and 10 / 10 is 1.

When to stop

When is the addition finished? Not as soon as both lists have ended: in Example 2 a carry of 1 is still waiting then. So the loop keeps going while l1 has a node, or l2 has a node, or the carry is not 0. Its last pass in Example 2 has no digits, only the carry, and adds the final node 1.

Building the result list

How do new digits get onto the end of the result? A variable named tail points at the last node so far, and each new node is attached to tail.next. The very first digit has no node before it, which would need a special case. A placeholder node made before the loop, called a dummy node, removes it: tail starts on the dummy, and the answer starts at the dummy's next.

Java Solution

The method addTwoNumbers works in these steps:

  1. First, create the placeholder node dummy, point tail at it, and set carry to 0.
  2. The parameters l1 and l2 point at the current node of each list and become null when that list ends. Loop while l1 has a node, or l2 has a node, or carry is not 0. Each pass of the loop is one column, and it starts with sum set to carry.
  3. If l1 still has a node, add its value to sum and move l1 to the next node. Do the same for l2.
  4. Attach a new node holding sum % 10 to tail.next, move tail onto it, and set carry to sum / 10 for the next column.
  5. When the loop ends, return dummy.next, the node with the ones digit of the sum.

Next to the method, the class has a small ListNode class, a build helper that makes a list from digits, and a show helper that prints a list like [7, 0, 8]. The main method runs both examples, then 81 + 0 with lists of different lengths, 5 + 5, and 0 + 0.

Java
public class AddTwoNumbers {

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

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);       // placeholder before the first digit
        ListNode tail = dummy;
        int carry = 0;
        while (l1 != null || l2 != null || carry != 0) {
            int sum = carry;
            if (l1 != null) {
                sum += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                sum += l2.val;
                l2 = l2.next;
            }
            tail.next = new ListNode(sum % 10); // the digit for this column
            tail = tail.next;
            carry = sum / 10;                   // carried to the next column
        }
        return dummy.next;
    }

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

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

    public static void main(String[] args) {
        System.out.println(show(addTwoNumbers(build(2, 4, 3), build(5, 6, 4))));
        System.out.println(show(addTwoNumbers(build(9, 9, 9), build(1))));
        System.out.println(show(addTwoNumbers(build(1, 8), build(0))));
        System.out.println(show(addTwoNumbers(build(5), build(5))));
        System.out.println(show(addTwoNumbers(build(0), build(0))));
    }
}

Running it prints:

Output
[7, 0, 8]
[0, 0, 0, 1]
[1, 8]
[0, 1]
[0]

Look at the second line, [0, 0, 0, 1], which is 1000. Its last node comes from a pass where both lists had ended and only the carry was left. With carry != 0 taken out of the loop condition, the same input prints [0, 0, 0], and 5 + 5 prints [0].

The third line, [1, 8], is 81 + 0. After the ones column l2 is null, so the 8 goes through on its own. The fourth line, [0, 1], is 5 + 5 = 10, and 10 is the smallest sum that needs an extra node. The last line shows that 0 + 0 still gives one node, [0], because l1 has a node on the first pass.

Complexity

The method walks both lists once, side by side, and does a fixed amount of work per column.

  • Time: O(max(m, n)) for lists of m and n nodes: each pass of the loop handles one column, there are as many columns as nodes in the longer list, and a final carry adds at most one more pass.
  • Space: O(1) besides the result. The result list has at most max(m, n) + 1 nodes. Apart from it, the method keeps only dummy, tail, sum and carry.

When the digits are stored most significant first, see Add Two Numbers II.