Add Two Numbers II

Add two numbers stored in linked lists with the most significant digit first, using two stacks.

Two non-negative whole numbers are each stored in a linked list, one digit per node, with the most significant digit in the first node. So 7243 is stored as 7, then 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 stored the same way.

Example 1
Input: l1 = [7, 2, 4, 3], l2 = [5, 6, 4]
Output: [7, 8, 0, 7]
Explanation: 7243 + 564 = 7807.
Example 2
Input: l1 = [2, 4, 3], l2 = [5, 6, 4]
Output: [8, 0, 7]
Explanation: 243 + 564 = 807.
Solution

The Idea

To add 7243 and 564 on paper, you write 564 under the last three digits of 7243 and start on the right. The ones column gives 3 + 4 = 7. The tens column gives 4 + 6 = 10, so you write 0 and pass the extra 1, called the carry, to the hundreds column. The answer, 7807, is written from right to left.

Here each number is a linked list: a chain of nodes, where each node holds one digit and a link, named next, to the node after it. The last node's next is null. The first node is called the head, and a method that adds the numbers gets only the two heads, l1 and l2. From a head it can walk forward along the links, but no node links back to the one before it.

So where are the ones digits? Look at the top half of the picture below. l1 is 7, 2, 4, 3 and l2 is 5, 6, 4, each drawn from its head. The nodes labelled ones digit, in orange, sit at the far end of each list, and not even in the same position: 3 is the fourth node of l1, and 4 is the third node of l2.

The lists l1 = 7, 2, 4, 3 and l2 = 5, 6, 4 with their ones digits, 3 and 4, at the far end from the head. Pushed onto stacks, 3 and 4 are on top. Popping pairs gives 3 + 4 = 7, 4 + 6 = 10 (digit 0, carry 1), 2 + 5 + 1 = 8, and 7, and putting each digit in front builds 7, 8, 0, 7.

Addition has to start with those orange nodes, and a walk from the head reaches them last. How can we read a list from the back when we can only walk it forward? Walk it once and put each digit on a stack. A stack is a pile of values: you push a value onto the top and pop the top value off, so the value pushed last comes off first.

The bottom left of the picture shows the stacks after both walks. The stack for l1 got 7, 2, 4 and 3, in that order, so 3 is on top. The stack for l2 has 4 on top. Popping one digit from each stack now gives the columns in the same order as on paper.

The rows under "Popped in pairs, ones column first" follow that order: 3 + 4 = 7, then 4 + 6 = 10, which gives the digit 0 and a carry of 1. Then come 2 + 5 + 1 = 8, and finally 7 on its own, because the stack for l2 is empty by then.

One question is left. The digits come out ones digit first: 7, 0, 8, and then the thousands digit 7. The answer must start with the thousands digit. So each new digit goes in front of the digits already built, and the result row in the picture reads 7, 8, 0, 7.

Solution Approach

Before the stacks, it is worth seeing why the lists cannot simply be turned into numbers. After that, three things need settling: how to store the digits, how a column gives its digit and carry, and how to put each digit in front. Reversing the lists in place is an optional way to save memory.

Why not plain numbers

Could we read 7, 2, 4, 3 into the number 7243, add 564, and split 7807 back into nodes? Only while the numbers fit in a Java long, which holds at most 19 digits, and nothing stops a list from having 30 nodes. Adding column by column never needs the whole number at once, so it works for any length.

Storing the digits on stacks

Which Java class should hold the digits? ArrayDeque, a queue in java.util that can add and remove at both ends, has the stack methods push, pop and isEmpty. The Java documentation recommends it over the older Stack class, which locks the object on every call. One stack per list, filled by one walk from the head, is all the preparation needed.

One column: digit and carry

What does one column write, and what does it pass on? Its sum is never more than 19, two 9s plus a carry of 1. The digit is sum % 10, the remainder after dividing by 10, and the carry is sum / 10, which Java rounds down: 1 for sums from 10 to 19, 0 below 10.

When one stack runs empty, as the stack for l2 does before the thousands column, its digit counts as 0, like the blank space on paper. And the adding must not stop as soon as both stacks are empty. In 999 + 1 a carry of 1 is still waiting then, and it becomes the leading digit of 1000.

Putting each digit in front

How do you put a node in front of a list? Make the new node with its next pointing at the current first node, and then treat the new node as the first one. A variable named head holds the first node. It starts as null, an empty list, so the first digit becomes a list of one node and no special case is needed.

Reversing the lists instead

The stacks hold a copy of every digit. Is there a way without them? If both lists are reversed in place first, by turning each next link around, the ones digits move to the heads. Plain column addition from the heads then works with no extra memory. The cost is that the caller's lists are changed, unless the method reverses them back at the end. The stack version only reads them.

Java Solution

The method addTwoNumbers works in these steps:

  1. First, create two stacks, s1 and s2, as ArrayDeque objects. A loop walks l1 from its head and pushes each digit onto s1, and a second loop does the same for l2 and s2.
  2. Set head, the first node of the result, to null, and carry to 0.
  3. Loop while s1 is not empty, or s2 is not empty, or carry is not 0. Each pass is one column: it starts sum at carry, then pops a digit from each stack that still has one and adds it.
  4. Put a new node holding sum % 10 in front, with head = new ListNode(sum % 10, head), and set carry to sum / 10 for the next column.
  5. When the loop ends, return head, which now holds the most significant 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 [8, 0, 7]. The main method runs both examples, 999 + 1 and 0 + 0, and then prints l1 from Example 1 once more.

Java
import java.util.ArrayDeque;
import java.util.Deque;

public class AddTwoNumbersII {

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

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        Deque<Integer> s1 = new ArrayDeque<>();   // digits of l1, ones digit on top
        Deque<Integer> s2 = new ArrayDeque<>();
        for (ListNode n = l1; n != null; n = n.next) {
            s1.push(n.val);
        }
        for (ListNode n = l2; n != null; n = n.next) {
            s2.push(n.val);
        }
        ListNode head = null;
        int carry = 0;
        while (!s1.isEmpty() || !s2.isEmpty() || carry != 0) {
            int sum = carry;
            if (!s1.isEmpty()) {
                sum += s1.pop();
            }
            if (!s2.isEmpty()) {
                sum += s2.pop();
            }
            head = new ListNode(sum % 10, head);  // new digit goes in front
            carry = sum / 10;
        }
        return head;
    }

    static ListNode build(int... digits) {
        ListNode head = null;
        for (int i = digits.length - 1; i >= 0; i--) {
            head = new ListNode(digits[i], head);
        }
        return head;
    }

    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) {
        ListNode l1 = build(7, 2, 4, 3);
        System.out.println(show(addTwoNumbers(l1, build(5, 6, 4))));
        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(0), build(0))));
        System.out.println("l1 afterwards: " + show(l1));
    }
}

Running it prints:

Output
[7, 8, 0, 7]
[8, 0, 7]
[1, 0, 0, 0]
[0]
l1 afterwards: [7, 2, 4, 3]

Look at the third line, [1, 0, 0, 0], which is 999 + 1 = 1000. Its first node, the 1, comes from a last pass where both stacks were already empty and only the carry was left. That pass happens because the loop condition includes carry != 0.

The fourth line shows that 0 + 0 still gives one node, [0]: each stack holds a 0, so the loop runs once. The last line prints l1 after Example 1 was added, and it is still [7, 2, 4, 3], because the method only reads the lists to fill the stacks.

Putting each digit in front is what keeps [7, 8, 0, 7] in the right order. A version that attaches each new node at the end of the result instead prints [7, 0, 8, 7] for Example 1, which reads as 7087.

Complexity

The method walks each list once to fill the stacks, then pops every digit once while adding.

  • Time: O(m + n) for lists of m and n nodes: the two walks push m and n digits, the adding loop pops each of them once, and a final carry adds at most one more pass.
  • Space: O(m + n) besides the result, because the two stacks hold a copy of every digit of both lists. Reversing the lists in place instead brings this down to O(1), at the price of changing the input.

When the digits are stored ones digit first, no stacks are needed: see Add Two Numbers.