Add Two Numbers solution explained
Add Two Numbers is solved by walking both linked lists together, adding the two digits plus a carry at each step, writing the last digit of that sum into a new node and carrying the rest forward. Because the digits are stored ones place first, this is exactly grade-school addition, it runs in O(max(m, n)) time, and the loop only needs to keep going while either list or the carry is left.
By Evin JohnPublished 6 min read
The task in plain words
Each list holds one decimal digit per node, and the head is the ones digit, then tens, then hundreds. So the list 5 → 4 → 9 means 945. Given two such lists, build a third list in the same format holding their sum. Numbers have no extra leading zeros, except the number zero itself, which is a single node holding 0.
| First list | Second list | Numbers | Result list |
|---|---|---|---|
| 5 → 4 → 9 | 7 → 7 | 945 + 77 = 1022 | 2 → 2 → 0 → 1 |
| 9 → 9 | 1 | 99 + 1 = 100 | 0 → 0 → 1 |
| 0 | 0 | 0 + 0 = 0 | 0 |
| 3 → 2 | 6 → 1 | 23 + 16 = 39 | 9 → 3 |
The second row is the one to say out loud early: a carry can outlive both input lists and create one extra node at the end.
What the interviewer is checking
This is a building exercise more than a search. It tests whether you can construct a new list cleanly while reading two others, handle uneven lengths without duplicated code, and remember the carry at the very end. It also opens a conversation about integer overflow, which is why the conversion shortcut is a trap: 64-bit integers in Java or C++ overflow a little above 9 × 10^18, and JavaScript numbers lose exact integers above about 9 × 10^15.
Common follow-ups
- Digits stored most significant first. Either reverse both lists, add, and reverse the result, or push digits onto two stacks and build the answer from the front.
- Do it without modifying the inputs. The standard answer already creates new nodes and leaves inputs alone.
- Subtract instead of add. Borrowing replaces carrying, and you must strip leading zeros from the result.
- Any base. Replace 10 with the base; the loop is unchanged.
A first answer: convert, add, convert back
Turn each list into an integer by adding digit times place value, add the integers, then peel digits off the sum with division and remainder. In Python this is correct because integers grow without limit. In most other languages it breaks somewhere past 16 to 19 digits, depending on the number type, which a 100-node input easily exceeds. Mention it, explain the overflow, and move on.
def add_by_conversion(a, b):
def to_int(node):
value, place = 0, 1
while node:
value += node.val * place
place *= 10
node = node.next
return value
total = to_int(a) + to_int(b)
sentinel = Node(0)
tail = sentinel
while True:
total, digit = divmod(total, 10)
tail.next = Node(digit)
tail = tail.next
if total == 0:
return sentinel.nextDigit-by-digit addition
Keep a carry starting at zero. On each step, add the carry to whatever digits the two lists still have at this position. The new digit is the sum mod 10 and the new carry is the sum divided by 10, which is either 0 or 1. Append the digit to the result and advance whichever input pointers are not finished. Stop only when both lists are done and the carry is zero. That single condition covers uneven lengths and the leftover carry together.
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
def add_two_numbers(a, b):
sentinel = Node(0)
tail = sentinel
carry = 0
while a or b or carry:
total = carry
if a:
total += a.val
a = a.next
if b:
total += b.val
b = b.next
carry, digit = divmod(total, 10)
tail.next = Node(digit)
tail = tail.next
return sentinel.nextclass ListNode {
constructor(val, next = null) {
this.val = val;
this.next = next;
}
}
function addTwoNumbers(a, b) {
const sentinel = new ListNode(0);
let tail = sentinel;
let carry = 0;
while (a !== null || b !== null || carry !== 0) {
let total = carry;
if (a !== null) { total += a.val; a = a.next; }
if (b !== null) { total += b.val; b = b.next; }
carry = Math.floor(total / 10);
tail.next = new ListNode(total % 10);
tail = tail.next;
}
return sentinel.next;
}Trace 99 + 1. Step one: 9 + 1 = 10, write 0, carry 1. Step two: the second list is empty, so 9 + 1 = 10 again, write 0, carry 1. Step three: both lists are empty but the carry is 1, so write 1. The result 0 → 0 → 1 reads as 100.
Time and memory
| Approach | Time | Extra memory | Risk |
|---|---|---|---|
| Convert to integers and back | O(m + n) digits, plus big-number cost | O(1) besides the result in Python | Overflow outside languages with unbounded integers |
| Digit-by-digit with carry | O(max(m, n)) | O(1) besides the result list | None if the carry check is in the loop condition |
The result list itself has at most max(m, n) + 1 nodes, so most interviewers describe the extra memory as constant apart from the output.
Inputs worth testing
- Lists of very different lengths, such as a ten-digit number plus a one-digit number.
- A carry that ripples all the way through, such as 9 → 9 → 9 plus 1.
- Both inputs equal to zero, which must return a single 0, not an empty list.
- No carry at all, to confirm you do not add a stray leading zero.
Typical mistakes
- Ending the loop when both lists are empty and forgetting the final carry.
- Writing three loops (both lists, then only the first, then only the second) and introducing a bug in one copy.
- Using the conversion shortcut in a language with fixed-size integers.
- Building the result backward and then reversing it, which is unnecessary when digits are already ones-first.
How to explain it out loud
Fictional example
- Candidate
- Since the ones digit comes first, I can add the way we do by hand: column by column with a carry.
- Candidate
- I keep going while either list has digits or the carry is one. Missing digits count as zero, so uneven lengths need no extra loop.
- Candidate
- A dummy head makes appending simple, and I return its next. It is linear in the longer list, and I avoid converting to numbers because that would overflow for long inputs.
Where to go next
Remove Nth Node From End of List practices the same sentinel idea on a deletion. Merge k Sorted Lists also builds a fresh list from several inputs, with a heap choosing each next node.
Natively as a study aid
Natively runs on Mac and Windows. While you practice, it can take a screenshot of a list problem like this one, read it and suggest the carry loop and the edge cases to check, such as a carry that outlives both lists. When you rehearse with a friend, the transcript it keeps lets you see whether you raised the overflow point yourself. More about the AI interview assistant.
Questions people ask
How do you solve Add Two Numbers?
Walk both lists together, add the two digits and the carry, write the sum's last digit to a new node and carry the rest. Keep looping while either list or the carry remains.
Why not convert the lists to integers and add them?
It works in Python, but in most languages long lists overflow 64-bit integers or lose precision, so interviewers expect digit-by-digit addition.
What is the time complexity of Add Two Numbers?
O(max(m, n)) for lists of lengths m and n. Apart from the result list, extra memory is constant.
What if the digits are stored most significant first?
Reverse both lists first, or push their digits onto two stacks, then add from the least significant end and build the result from the front.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
