C++ 0445.cpp
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
vector<int> a, b;
while (l1)
{
a.push_back(l1->val);
l1 = l1->next;
}
while (l2)
{
b.push_back(l2->val);
l2 = l2->next;
}
if (a.size() < b.size())
a.insert(a.begin(), b.size() - a.size(), 0);
if (b.size() < a.size())
b.insert(b.begin(), a.size() - b.size(), 0);
int carry = 0;
ListNode* next = nullptr;
for (int i = a.size() - 1; i >= 0; i--)
{
auto sum = carry + a[i] + b[i];
carry = sum / 10;
auto current = new ListNode(sum % 10, next);
next = current;
}
if (carry > 0)
next = new ListNode(carry, next);
return next;
}
};
Difficulty
and has an acceptance rate of about 63% (900k+ submissions).
Typical patterns to solve this problem:
- Linked List
- Math
- Stack
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The presented implementation solves the classic problem of adding two non-negative integers where each digit is stored in a singly-linked list node. The digits are stored in forward order, meaning the most significant digit appears at the head of the list. The algorithm first extracts the digits into random-access containers, equalizes their lengths, then performs a right-to-left addition while propagating the carry. The result is built as a new linked list in forward order and returned to the caller.
Input Normalization
The first phase walks each input list and copies the node values into a vector<int>. This conversion provides constant-time indexed access, which simplifies the later addition step.
vector<int> a, b;
while (l1)
{
a.push_back(l1->val);
l1 = l1->next;
}
while (l2)
{
b.push_back(l2->val);
l2 = l2->next;
}
By iterating until the pointer becomes nullptr, the code gracefully handles empty input lists, producing an empty vector for a nullptr argument.
Size Equalization
Because the addition proceeds from the least significant digit, the two vectors must share the same length. The implementation pads the shorter vector with leading zeros. This ensures that each index i refers to digits that align by significance.
if (a.size() < b.size())
a.insert(a.begin(), b.size() - a.size(), 0);
if (b.size() < a.size())
b.insert(b.begin(), a.size() - b.size(), 0);
The use of insert at the beginning preserves the original order of the more significant digits while extending the vector to the required size.
Summation Loop
The core addition runs a reverse for loop over the vectors, accumulating the sum of corresponding digits together with any carry from the previous iteration. The carry is computed by integer division, and the digit to store is obtained via modulus. A new ListNode is allocated for each digit, linking it to the previously created node via the next pointer. This builds the result list from tail to head without needing a separate traversal to locate the tail.
int carry = 0;
ListNode* next = nullptr;
for (int i = a.size() - 1; i >= 0; i--)
{
auto sum = carry + a[i] + b[i];
carry = sum / 10;
auto current = new ListNode(sum % 10, next);
next = current;
}
The constructor ListNode(value, next) directly sets the next field, avoiding an extra assignment after node creation.
Final Carry Handling
After processing all digit positions, a leftover carry indicates an overflow beyond the most significant digit. The algorithm checks for this condition and, if necessary, creates an additional node that becomes the new head of the result list.
if (carry > 0)
next = new ListNode(carry, next);
This step ensures that inputs such as 9 -> 9 plus 1 correctly produce 1 -> 0 -> 0.
Edge Cases Handled
The code naturally accommodates several boundary situations. When both input lists are empty, the vectors remain empty, the loop body is skipped, and the final carry check yields nullptr, representing a zero result. When one list is longer than the other, the padding logic equalizes lengths, allowing the addition loop to treat both vectors uniformly. A final carry greater than zero is explicitly turned into a new leading node, covering cases where the sum introduces an extra digit. The use of while (l1) and while (l2) loops also prevents dereferencing null pointers, safely terminating at the end of each list.
Performance Optimizations
The algorithm leverages random-access vectors to avoid repeated traversal of the linked lists during addition. By converting the lists to vectors, the addition step can index digits directly, which is more cache-friendly than walking two linked lists in parallel. The construction of the result list proceeds in reverse order, linking each newly created node to the previously built sub-list. This eliminates the need for a tail pointer or a separate pass to reverse the list, thereby reducing the number of pointer updates and memory allocations. Additionally, the ListNode constructor that accepts both value and next pointer consolidates node initialization into a single operation, minimizing the overhead of separate field assignments.
ELI5 - Simplified Explanation
Imagine you have two long trains made of brightly colored blocks. Each block has a special number painted on it. This code starts by taking every single block from both trains and lining them up in two rows on a table so they are very easy to see.
Since the trains might be different lengths, the code adds invisible empty blocks to the shorter train so both rows have exactly the same number of blocks. Now comes the fun part. Starting from the very last blocks at the end of the rows, the code adds the numbers on the two blocks together. If the two numbers make a big pile that is ten or higher, the code puts a tiny sticky note called a carry in the next spot to remember the extra part for the next step.
As it works backward toward the front of the trains, it creates a brand new train of blocks. Each new block keeps the right amount from the addition and attaches itself to the piece made before it. If there is still a sticky note left over after checking all the blocks, one final piece is added to the very front of the new train to hold that last bit. This finished chain of blocks is the answer that shows the sum.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | Rust | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 2: Add Two Numbers
- problem 1634: Add Two Polynomials Represented as Linked Lists
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality