The 30 second answer
The digits are stored in reverse order, one per node, so I can add from the heads and carry forward just as I would on paper. I walk both lists with a dummy head, write sum modulo 10 as the next node, and keep sum / 10 as the carry. A leftover carry after both lists end becomes a new node.
Problem You are given two non-empty linked lists representing two non-negative integers, with digits stored in reverse order, one digit per node. Add the two numbers and return the sum as a list in the same format. Original: LeetCode 2: Add Two Numbers.
Understanding the prompt The reverse order is a gift: you start at the least significant digit, which is where addition has to start. The lists may have different lengths. The official problem forbids leading zeros, except the number 0 itself. The sum may have one more digit than the longer input.
Pattern recognition Merge two sequences with a dummy head, except the combine step is digit addition plus carry rather than a comparison.
Brute force Decode both lists into integers, add, and encode the result. That overflows a 64-bit integer on long official inputs and is not what the problem is testing.
Optimal A dummy head, a tail, and a carry starting at 0. While either list is non-null or the carry is non-zero, add the current digits (treating a missing node as 0) and the carry, append a node with the digit sum % 10, and set carry to sum / 10. Return dummy.next.
Alternatives If the digits were stored in forward order, you would reverse both lists first, or use a stack, or recurse to the tails. That is a different problem (Add Two Numbers II).
Java solution
public class AddTwoNumbers {
static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
static ListNode list(int... a) {
var dummy = new ListNode(0);
var t = dummy;
for (int x : a) {
t.next = new ListNode(x);
t = t.next;
}
return dummy.next;
}
static String str(ListNode h) {
var sb = new StringBuilder("[");
for (ListNode p = h; p != null; p = p.next) {
if (sb.length() > 1) sb.append(", ");
sb.append(p.val);
}
return sb.append("]").toString();
}
static ListNode addTwoNumbers(ListNode a, ListNode b) {
var dummy = new ListNode(0);
var t = dummy;
int carry = 0;
while (a != null || b != null || carry != 0) {
int sum = carry;
if (a != null) { sum += a.val; a = a.next; }
if (b != null) { sum += b.val; b = b.next; }
t.next = new ListNode(sum % 10);
t = t.next;
carry = sum / 10;
}
return dummy.next;
}
public static void main(String[] args) {
System.out.println(str(addTwoNumbers(list(2, 4, 3), list(5, 6, 4)))); // [7, 0, 8]
System.out.println(str(addTwoNumbers(list(0), list(0)))); // [0]
System.out.println(str(addTwoNumbers(list(9, 9, 9, 9, 9, 9, 9), list(9, 9, 9, 9)))); // [8, 9, 9, 9, 0, 0, 0, 1]
}
}Complexity O(max(n, m)) time, O(1) extra space besides the output list.
Edge cases
- Official samples: 2 -> 4 -> 3 plus 5 -> 6 -> 4 is 7 -> 0 -> 8, because 342 + 465 = 807; 0 + 0 is 0; 9,9,9,9,9,9,9 plus 9,9,9,9 is 8,9,9,9,0,0,0,1.
- Lists of different lengths, and a final carry that creates an extra node.
Follow-ups
- Add Two Numbers II stores the digits in forward order.
- The same carry loop adds two binary strings or two arrays of digits.
Tests [2,4,3] plus [5,6,4] returns [7,0,8]. [0] plus [0] returns [0]. [9,9,9,9,9,9,9] plus [9,9,9,9] returns [8,9,9,9,0,0,0,1].
How to say it in the interview "The digits are already in reverse order, so I add from the heads with a carry, just as on paper. I write the digit modulo 10, keep the carry, and I do not forget a leftover carry after both lists end. A dummy head keeps the code short."
Sources (1)
- LeetCode 2: Add Two Numbersleetcode.com