Add Two NumbersMedium

linked list math

Two numbers are stored as linked lists, least-significant digit first. Add them the way you would on paper: walk both lists together, write (a + b + carry) mod 10, and push the overflow into the next column.

 
l1 (digits, least-significant first)
l2
result (built on a dummy head)
Press play to add the two numbers column by column.
Metrics
a = l1.val
b = l2.val
0
carry
a + b + carry
Simultaneous traversal
Legend
Current node (a, b)
Consumed node
Result digit
How it works

Reverse order is a gift: the heads of both lists are the ones place, so you add left-to-right and the carry always flows forward into the next node.

One pass, no number ever reconstructed (which would overflow for long lists). Time O(max(m, n)), extra space O(1) beyond the result list. The loop also runs while carry > 0, which is what grows 999 + 1 into a 4-digit answer.

0 / 0