A-040● Day 402026.06.15mediumleetcode #2neetcode150
Add Two Numbers
#linked-list#math#recursion
01
Problem
· problemYou 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.
constraints
- · 1 ≤ number of nodes in each list ≤ 100
- · 0 ≤ Node.val ≤ 9
- · No leading zeros except for the number 0 itself
// paraphrased summary — see source for full text
examples
02
Pre-solve
· pre-solve● 1list shown→● 2select→● 3reveal
- ☐Can the two lists have different lengths?
- ☐What happens if the final addition produces a carry? (e.g., 999 + 1 = 1000)
- ☐Can we modify the input lists?
- ☐Can a node's value exceed 9? Could we have a node with value 12?
- ☐Why do we return dummy.next instead of dummy itself?
- ☐Would it be more efficient to reverse both lists, add them, then reverse the result?
- ☐Do we need to handle negative numbers?
- ☐Doesn't the dummy node stay at the front of the result?
check the items you would ask, then press confirm
// session-only state — refresh resets (repeatable practice)
03
Logic Structure
· logic● 1slots shown→● 2pick per slot→● 3reveal
// pick one code line per slot to assemble the algorithm flow. no typing — just the logic skeleton.
step 1· Create dummy node
○
dummy = ListNode()
○
cur = ListNode()
○
dummy = l1
step 2· Initialize carry
○
carry = 0
○
carry = 1
○
carry = l1.val + l2.val
step 3· Loop while nodes or carry exist
○
while l1 or l2 or carry:
○
while l1 or l2:
○
while l1 and l2:
step 4· Extract node values│ nested
○
v1 = l1.val if l1 else 0
○
v1 = l1.val if l1 else None
○
v1 = l1.next.val if l1 else 0
step 5· Sum current digits and carry│ nested
○
val = v1 + v2 + carry
○
val = v1 + v2
○
val = (v1 + v2) * carry
step 6· Extract carry via integer division│ nested
○
carry = val // 10
○
carry = val % 10
○
carry = val / 10
step 7· Create and append new node│ nested
○
cur.next = ListNode(val)
○
cur = ListNode(val)
○
cur.next = ListNode(val // 10)
pick one option per slot
// format: slot — recursive / DP patterns use ordering / state-first formats. ADR-08 follow-up.
04
Solve · Trace
· solvemental dry-run cases
// walk each case in your head; expand the worked example below if stuck.
case 1
[2,4,3] [5,6,4]→
[7,0,8]
case 2
[0] [0]→
[0]
case 3
[9,9,9,9,9,9,9] [9,9,9,9]→
[8,9,9,9,0,0,0,1]
// UI does not walk-through — you do the dry-run mentally. Expand the worked example if stuck.