LeetCode 2: Add Two Numbers is a Medium linked list problem. This Python walkthrough develops a digitwise carry solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Linked List |
| Reusable pattern | digitwise carry |
| Complexity | O(max(m,n)) time and O(max(m,n)) output space |
Recognizing the pattern
Linked-list solutions depend on preserving reachability while rewiring a constant number of pointers. Dummy nodes remove many head-only special cases.
For this problem specifically, walk both reverse-order digit lists, add available digits plus carry, and append the ones digit while carrying the tens digit. The invariant worth writing beside the code is: The output prefix represents the exact sum of the processed digit positions.
Step-by-step algorithm
- Identify the input state consumed by
addTwoNumbers(l1, l2)and initialize the data required by the digitwise carry pattern. - Walk both reverse-order digit lists, add available digits plus carry, and append the ones digit while carrying the tens digit.
- After each update, verify the page’s central invariant: The output prefix represents the exact sum of the processed digit positions.
- Finish only after the boundary behavior is covered: A final carry creates a new node; lists can have different lengths.
Python solution
LeetCode supplies the list, tree, or graph node class referenced by this method. The downloadable test suite includes compatible local node definitions so the implementation can also run outside the judge.
class Solution:
def addTwoNumbers(self, l1, l2):
dummy = tail = ListNode()
carry = 0
while l1 or l2 or carry:
total = carry
if l1: total += l1.val; l1 = l1.next
if l2: total += l2.val; l2 = l2.next
carry, digit = divmod(total, 10)
tail.next = ListNode(digit)
tail = tail.next
return dummy.nextReading the implementation
The main entry point is addTwoNumbers(l1, l2). The named working state includes dummy, carry, total, tail; those variables make the digitwise carry state visible instead of hiding it in incidental control flow.
A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. In concrete terms, walk both reverse-order digit lists, add available digits plus carry, and append the ones digit while carrying the tens digit.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. Walk both reverse-order digit lists, add available digits plus carry, and append the ones digit while carrying the tens digit. Each update records the current item without invalidating earlier decisions; consequently, the output prefix represents the exact sum of the processed digit positions.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O(max(m,n)) time and O(max(m,n)) output space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
Copying values into an array makes indexing easy but abandons the intended pointer-space constraint and node identity. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
assert listed(Solution().addTwoNumbers(linked([2,4,3]),linked([5,6,4]))) == [7,0,8]Common mistakes and edge cases
- Problem-specific boundary: A final carry creates a new node; lists can have different lengths.
- Pattern-level pitfall: Save the next node before changing a link, terminate reused tails, and check whether the original head can be removed.
- Invariant check: after every update, confirm that the output prefix represents the exact sum of the processed digit positions.
Interview review checklist
- Explain why digitwise carry matches the structure of this input.
- State the invariant in one sentence before tracing code: The output prefix represents the exact sum of the processed digit positions.
- Derive O(max(m,n)) time and O(max(m,n)) output space from how many times each element or state is visited.
- Test the boundary explicitly: A final carry creates a new node; lists can have different lengths.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 141. Linked List Cycle · Next: 21. Merge Two Sorted Lists