Add Two Numbers
Add numbers stored digit by digit in lists
DSA, Medium, Linked List
Which structure or algorithm, and what does it cost.
Two whole numbers are each stored in a linked list, one digit per node, with the ones digit first. For example, [7, 1, 5] stands for 517. Return the sum of the two numbers as a list in the same layout. There are no leading zeros, except that the number 0 is the list [0]. A node has val and next. Your code gets the first node of each list and returns the first node of the result. The examples write a list as its values in order, such as [7, 1, 5], only to keep them short.
Examples
Constraints
- 1 <= length of each list <= 100,000.
- Each digit is a whole number from 0 to 9.
- No leading zeros, except for the single number 0.
Your answer must contain
- The simple method and when it fails; the better method; code; time and memory cost; a hand trace of example 1 showing the carry.
Target Aim for O(n) time, where n is the longer length, and O(1) extra memory besides the result.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Think about how you add two numbers on paper. You start from the right and carry a digit. Which end of these lists comes first?
Hint 2 the approach
The lists already start at the ones digit. Add digit by digit, pass the carry on, and build the answer one node at a time.
Hint 3 the key step
Your loop ends when both lists run out. What if the carry is still 1 at that moment?
Walkthrough
Full walkthrough brute force to best
Brute force
Turn each list into one integer, add the two integers, and split the sum back into digits. With big-integer support this is short, but with 100,000 digits it needs big-number arithmetic. In a language with 64-bit integers it overflows after about 18 digits, so the method fails on large inputs. The cost is O(n) time and O(n) memory for the digits and the two numbers.
Best method
Do what you do on paper, from the ones digit. Keep a carry that starts at 0. At each step add the current digit of each list, using 0 for a list that has ended, plus the carry. The new digit is the total modulo 10, and the new carry is the total divided by 10, rounded down. Append the digit to the result. Keep going while either list has digits left or the carry is not 0, so a final carry becomes one more digit. A dummy node in front of the result avoids a special case for the first digit. Each digit is touched once, and the sum is exact for any length.
Hand trace
Run on a = [7, 1, 5] and b = [6, 8]. Carry starts at 0. Step 1: 7 + 6 + 0 = 13, write 3, carry 1. Step 2: 1 + 8 + 1 = 10, write 0, carry 1. Step 3: only a has a digit, so 5 + 0 + 1 = 6, write 6, carry 0. Both lists are done and the carry is 0, so stop. The result is [3, 0, 6].
Code
class Node:
def __init__(self, val, nxt=None):
self.val = val
self.next = nxt
def add_two_numbers(a, b): # a and b are the first nodes of the two lists
dummy = tail = Node(0)
carry = 0
while a or b or carry: # carry keeps the loop going past the end of both lists
total = carry
if a:
total += a.val
a = a.next
if b:
total += b.val
b = b.next
tail.next = Node(total % 10)
tail = tail.next
carry = total // 10
return dummy.next # the first node of the result
# Test helper, not part of the answer: builds a list of nodes from values and reads it back.
def build(values):
head = None
for v in reversed(values):
head = Node(v, head)
return head
def to_values(head):
out = []
while head:
out.append(head.val)
head = head.next
return outTime and memory
O(n) time, where n is the longer length: one step per digit. O(1) extra memory besides the result list, which has at most n + 1 digits.
Common mistakes
- Stopping when both lists end and dropping a last carry. 999 + 1 must give four digits.
- Crashing when the lists have different lengths. Treat a finished list as the digit 0.
- Storing the whole total as a digit. Write total modulo 10 and carry the rest.