You get two non-empty linked lists, l1 and l2. Each one stores a non-negative whole number one digit per node, with the most significant digit first, so 386 is stored as 3 → 8 → 6. Neither number has extra leading zeros, apart from the number 0 itself.
Add the two numbers and return their sum as a linked list in the same format. Try to do it without reversing the input lists.
Example 1
Input: l1 = [3, 8, 6], l2 = [5, 9] Output: [4, 4, 5] Why: 386 + 59 = 445
2 more examples and the constraints
Example 2
Input: l1 = [9, 9], l2 = [1] Output: [1, 0, 0] Why: 99 + 1 = 100, one digit longer
Example 3
Input: l1 = [0], l2 = [0] Output: [0] Why: 0 + 0 = 0
Constraints
- 1 ≤ nodes in each list ≤ 100
- 0 ≤ node value ≤ 9
- No number has leading zeros, except 0 itself
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Reverse, add, prependO(m + n)
- Two stacksO(m + n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for two 100-digit numbers | Verdict |
|---|---|---|---|
| Reverse, add, prepend | O(m + n) | Fast, but changes the input | |
| Two stacks | O(m + n) | Best; input left untouched |
m and n = number of digits in l1 and l2.
Edge cases to test
- A final carry. [9, 9] + [1] needs a new leading node: [1, 0, 0]. Keep looping while the carry is not 0.
- Different lengths. [5] + [9, 9, 5]: the shorter stack empties first and counts as 0.
- Both zero. [0] + [0] must return [0], not an empty list.
- Long numbers. 100 digits do not fit in any built-in integer type, so never convert the lists to numbers.
Common mistakes
- Converting each list to an integer, which overflows long before 100 digits.
- Dropping the last carry, so 99 + 1 comes out as [0, 0].
- Appending digits at the tail of the result, which gives the sum backwards.
How to talk through it
- 1Clarify. Most significant digit first? Can I change the input lists? How long can they be?
- 2Say why it is awkward. Addition starts at the ones, but a singly linked list only walks from the front.
- 3Offer the reversal. Reverse, add as usual, prepend; then note that it rewires the input.
- 4Code the stacks. Stacks give the digits back from the tail; prepending keeps the result in order.
- 5Test out loud. Run 99 + 1, different lengths, and 0 + 0 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?