Add Two Numbers
Add two numbers stored as digit lists, ones digit first, the way you add columns by hand with a carry.
The problem
You get two non-empty linked lists that each store a non-negative integer, one digit per node, with the ones digit first (so 618 is stored as [8, 1, 6]). Add the two numbers and return the sum as a linked list in the same form. Neither number has leading zeros, except the number 0 itself.
Input l1 = [4, 7, 2], l2 = [9, 5]
Output [3, 3, 3]
The lists hold 274 and 59, and 274 + 59 = 333.
Input l1 = [9, 9], l2 = [1]
Output [0, 0, 1]
99 + 1 = 100: the carry ripples through both digits and adds a new node at the end.
Key constraint: Each list can have up to 100 digits, far more than a 64-bit integer can hold, so you can't convert the lists to numbers and add those.
How to spot the pattern
- Numbers are stored digit by digit, lowest digit first, which is the order you add them by hand.
- The numbers can be longer than any built-in integer type.
The idea
This is column addition from school. Because the lowest digit comes first, you can walk both lists together, add the two digits plus the carry, write sum % 10 into a new node and carry sum / 10 into the next column. Keep going while either list has digits left or a carry remains, so a final carry becomes one extra node.
Brute force: Turn both lists into integers, add them and turn the sum back into a list; with up to 100 digits this overflows 64-bit integers in most languages.
Step by step
- 1Create a dummy node, a
tailpointer andcarry = 0. - 2While
l1orl2still has nodes, orcarryis not 0, add the current digits (0 for a list that has ended) tocarry. - 3Append a node holding
sum % 10and setcarrytosum / 10, using integer division. - 4Move
l1andl2forward when they have nodes, and at the end returndummy.next.
See the pattern move
The linked lists pattern on a small example. Step through it, or press play.
Code
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode()
tail = dummy
carry = 0
while l1 or l2 or carry:
total = carry
if l1:
total += l1.val
l1 = l1.next
if l2:
total += l2.val
l2 = l2.next
carry, digit = divmod(total, 10)
tail.next = ListNode(digit)
tail = tail.next
return dummy.nextComplexity
Time
O(max(m, n))
Space
O(max(m, n))
One pass over the longer list; the only memory used is the result, which has at most max(m, n) + 1 nodes.
Watch out for
- Stopping when both lists end and forgetting the last carry, which turns 99 + 1 into [0, 0] instead of [0, 0, 1].
- Moving
l1orl2forward after it has already become null. - Converting the lists to numbers first, which overflows for long inputs (Python's big integers hide the problem, but the interviewer wants the digit-by-digit idea).
Follow-up questions
What if the digits are stored with the most significant digit first?
Push both lists' digits onto two stacks (or reverse both lists), then add from the tops of the stacks and build the result by inserting each new node at the front. That is Add Two Numbers II.
Why does storing the ones digit first make this easy?
Carries move from lower digits to higher ones, so handling the ones digit first means every carry is known before you need it. In the other order you would have to look ahead or reverse the lists first.
In Hinglish
School wala jod hai: dono digits plus carry, node mein sum % 10 likho aur carry aage bhejo. Aakhir mein carry bacha ho toh ek extra node banana mat bhoolna.