Add Two Numbers
MediumYou are given two linked lists representing two non-negative integers. The digits are stored in reverse order, meaning the first node is the ones digit. Add the two numbers and return the sum as a new linked list.
Remember doing addition with paper and pencil in school? You lined up numbers by their ones, tens, and hundreds columns, added each column from right to left, and carried over a 1 whenever the sum reached 10 or more. Because the linked lists are already in reverse order, you can add them column by column just like grade-school math!
Reference: LeetCode #2 • Add Two Numbers
Linked List Addition Engine
Optimal: Elementary Math Simulation (With Carry)Column 2 (Tens): 4 + 6 = 10 (Carry 1!)
TRAVERSINGAdd the tens digits: 4 + 6 + 0 (carry) = 10. Since 10 is 10 or greater, write down 0 and carry over 1 to the next column!
Sum is 10: node gets 0 (10 % 10), carry becomes 1.Why is Column Math the Best Solution?
Why converting to normal numbers crashes, and why elementary math works on numbers of any size.
Convert to Number
Read both lists into normal numbers, calculate 342 + 465 = 807, and turn 807 into a list.
Numbers Get Too Big!
Numbers can have 100 digits! Standard computer variables break after 18 digits. Trying to hold 100 digits crashes.
Reversed Order is a Gift
Notice: The list starts at the ones digit! This is exactly how we write numbers when adding by hand on paper.
Add Column by Column
Sum = digit1 + digit2 + carry. New digit is sum % 10. Next carry is sum / 10.
Build in One Pass
Create answer nodes as you step forward. Fast O(n) time, minimal memory, and zero risk of numbers overflowing!
Optimal: Elementary Math Simulation (With Carry)
We step through both lists together once. Adding two single digits takes only 1 instant step.
We only use a couple of simple variables (like carry and sum). We do not store extra lists in memory.
Example Test Cases
Simple examplesRules & Limits
Constraints- Up to 100 digits
The number of nodes in each linked list is in the range
[1, 100](exceeds 64-bit integer limits). - Single digits (0 to 9)
Each node stores a single digit
0 ≤ Node.val ≤ 9. - No leading zeros
Numbers will never start with 0, except for the number 0 itself.
- Reversed order
The first node is the ones digit, making column math easy to start right away.
Important Things to Remember
Key Lessons
Creating a linked list from scratch is messy because you don't have a first node yet. Making a fake starting node (dummy = ListNode(0)) keeps your code simple. When done, just return dummy.next!
Use while (l1 || l2 || carry). This loop keeps running if one list is longer than the other, or if there is a leftover carry 1 at the very end.
Don't turn the list into a normal number first. 100-digit numbers crash normal variables. Adding node-by-node is simple, works for numbers of any size, and uses very little memory.