Add Two Numbers
You are given two non-negative integers, each stored as a singly linked list of single digits with the ones digit at the head — the digits are in reverse order, so 342 is stored as 2 → 4 → 3. Return their sum in the same form: a new linked list of digits, ones-first. The two lists may have different lengths, and the result may be longer than both (a final carry adds one more digit). Neither input has leading zeros, except the number 0 itself, which is the single node [0].
- The number of nodes in each list is in the range [1, 100]
- 0 <= Node.val <= 9
- No leading zeros except the number 0 itself.
l1 = [2,4,3], l2 = [5,6,4][7,0,8]l1 = [0], l2 = [0][0]l1 = [9,9,9,9], l2 = [9,9,9][8,9,9,0,1]We are given two numbers, but not as integers — each is a chain of single digits, one digit per node, stored reversed so the ones place comes first. We must add them and return the sum in the same reversed-digit form. The reversal looks like an obstacle; it is actually a gift, and seeing why is the whole insight.
The obvious plan: walk each list to rebuild its integer, add the two integers, then break the sum back into digit nodes. It reads cleanly and, in a language with unbounded integers like Python, it even works. But it quietly leans on something the problem is engineered to break. Each list can hold up to 100 digits — a 100-digit number. In most languages (C++, Java, Go) a machine integer tops out around 19 digits; feeding it a 100-digit value overflows and silently produces garbage. The shortcut converts the numbers to a form that cannot hold them. The digit-by-digit structure we were given is precisely the representation that has no size limit — so the robust solution should add in that representation directly, never assembling the whole number at all.
Think about how you add by hand. You line the numbers up on the right and start at the ones column, because a carry only ever flows from a smaller place to a larger one — right to left. That direction is the catch when digits are stored most-significant-first, because you'd have to reach the ends of both lists before you could even begin. But here the lists are reversed: the head of each list is the ones digit. Walking both lists forward from their heads therefore visits the columns in exactly the order hand-addition needs — ones, then tens, then hundreds. The reversal has pre-aligned the numbers for us. A single simultaneous forward traversal of both lists is long addition.
Walk both lists together. At each step take a digit from each (0 if that list has run out — a shorter number is just padded with leading zeros in the higher places), add them plus the carry left over from the previous column. That total is between 0 and 18 + a carry, so the digit we write is total % 10 and the carry we pass to the next column is total // 10 (either 0 or 1). We build the result with a dummy node: a throwaway node sitting before the real head so that appending the first digit is the same code as appending every other digit — no special case for an empty result. At the end we return dummy.next, the real head.
dummy = Node(0) # placeholder so the first append is not a special case
curr = dummy
carry = 0
while l1 or l2 or carry: # keep going while ANY of the three has work
v1 = l1.val if l1 else 0 # a missing digit counts as 0
v2 = l2.val if l2 else 0
total = v1 + v2 + carry
carry = total // 10 # 0 or 1, flows to the next column
curr.next = Node(total % 10) # the digit stored in this column
curr = curr.next
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return dummy.nextl1 or l2 or carry — and that final or carry is the piece everyone forgets. When both lists end but the last column produced a carry, there is still one more digit to write, and it lengthens the result beyond either input. Adding 9999 + 999, the highest column gives 9 + 0 + 1 = 10: after both lists are exhausted a carry of 1 remains, and it must become its own new leading node, turning a 4-digit and 3-digit input into a 5-digit answer. Dropping the or carry test silently loses that top digit. The if l1 else 0 on each side is the same idea one level down: it lets lists of different lengths add correctly by treating the shorter one's missing high digits as zero, instead of crashing when one list ends first.The cost is O(max(N, M)) time — one pass over the longer list — and O(max(N, M)) space for the result we must produce. Two habits generalize past this problem. First, simulate the pencil-and-paper method directly when a problem hands you a number in an unusual representation; don't rush to convert to a native integer that may not fit — the given representation is often chosen because it has no size ceiling. Second, meet the dummy-node builder: whenever you construct a linked list from nothing, a throwaway head node erases the "is this the first element?" special case, and you'll reuse it unchanged in Merge Two Sorted Lists and anywhere a list is assembled node by node. The one piece of genuine state here — the carry — is a value threaded from each step to the next; spotting "what single fact must survive between iterations" is the same skill that runs through the fast/slow and reversal problems ahead.