Add Two Numbers
Master this topic with zero to advance depth.
Add Two Numbers
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Visual Representation
(2 -> 4 -> 3) + (5 -> 6 -> 4) = 7 -> 0 -> 8
Explanation: 342 + 465 = 807.Examples
Level I: Iterative (Elementary Math)
Intuition
Iterate through both lists, adding digits along with a carry. Create a new node for each digit of the sum.
Detailed Dry Run
l1=[2,4], l2=[5,6].
- 2+5=7, carry=0.
- 4+6=10, carry=1. Node 0.
- Final carry 1. Node 1. Result: 7->0->1.
⚠️ Common Pitfalls & Tips
Be careful with the final carry; don't forget to add a node for it if it's non-zero.
Level II: Recursive
Intuition
Treat the addition of two lists as a recursive operation: add the current nodes and carry, then recurse for the next nodes.
Detailed Dry Run
l1=[2,4], l2=[5,6].
- Add(2, 5, 0): val=7, next=Add(4, 6, 0).
- Add(4, 6, 0): val=0, next=Add(null, null, 1).
- Add(null, null, 1): val=1, next=null. Result: 7->0->1.
⚠️ Common Pitfalls & Tips
Ensure the base case handles the final carry correctly.
Level III: Optimized Iterative (In-place Re-use)
Intuition
To optimize space, we can re-use the nodes of the longer list instead of creating new ones. However, this is only possible if modifying the input is allowed.
- Determine which list is longer (or just pick one).
- Add values and carry to the existing nodes.
- If the list ends while carry > 0, append a new node.
Detailed Dry Run
l1=[2,4], l2=[5,6,7]. Re-use l2.
- l2[0] = (2+5)%10 = 7. carry=0.
- l2[1] = (4+6)%10 = 0. carry=1.
- l2[2] = (1+7)%10 = 8. carry=0. Return l2.
⚠️ Common Pitfalls & Tips
Modifying input lists is generally discouraged unless specified, but it's a valid 'memory-constrained' strategy.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.