Add Two Numbers
LeetCode 2 · Medium · solution, intuition & step-by-step walkthrough
Grade-school addition with a carry.
This is how I solved Add Two Numbers (LeetCode 2), a medium problem from the Arithmetic pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
The digits are stored least-significant first, which is exactly the order you add by hand. Walk both lists together, add digits plus carry, write sum % 10 and carry sum // 10.
Approach
- 1
Loop while either list or the carry remains.
- 2
Missing digits count as 0.
- 3
Append a node with sum % 10; carry = sum // 10.
How I solved it
Digit-by-digit additionPythonO(max(m,n)) time
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(-1)
temp = dummy
carry =0
while l1 or l2 or carry!=0:
cur_sum = (l1.val if l1 else 0) + (l2.val if l2 else 0) + carry
new_node = ListNode(cur_sum%10)
carry = cur_sum//10
temp.next = new_node
temp = temp.next
if l1:
l1=l1.next
if l2:
l2=l2.next
return dummy.next
Add Two Numbers — FAQ
What is the intuition behind Add Two Numbers?
The digits are stored least-significant first, which is exactly the order you add by hand. Walk both lists together, add digits plus carry, write sum % 10 and carry sum // 10.
How do you solve Add Two Numbers (LeetCode 2)?
1. Loop while either list or the carry remains. 2. Missing digits count as 0. 3. Append a node with sum % 10; carry = sum // 10.
What is the time and space complexity of Add Two Numbers?
Time: O(max(m, n)). Space: O(max(m, n)) output. (Accepted approach: Digit-by-digit addition.)
What are common mistakes in Add Two Numbers?
Keep looping for a final carry (999 + 1).