Explain digit-by-digit addition with carry.
Skip to solutionKEEP THE
mediumDSA
How do you add two numbers stored as linked lists?
1.1k views
01
Understand the problem
linked-listmath
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Nudge consolestandby
Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.
03
Study the solution
Walk both lists together, summing corresponding digits plus a carry, creating a new node for sum % 10 and carrying sum / 10. Continue until both lists and the carry are exhausted. A dummy head simplifies building the result. O(max(m,n)).
Solution ready — 2 min read
Classified // press E to declassify
04
Read the code
Digit-by-digit with carry
Run Playgroundclass ListNode:
def __init__(self, val, nxt=None):
self.val, self.next = val, nxt
def add_two_numbers(l1, l2):
dummy = tail = ListNode(0)
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.next
# --- demo --- 342 + 465 = 807 (digits stored reversed)
def build(vals):
head = None
for v in reversed(vals): head = ListNode(v, head)
return head
def to_list(head):
out = []
while head: out.append(head.val); head = head.next
return out
print(to_list(add_two_numbers(build([2, 4, 3]), build([5, 6, 4])))) # [7, 0, 8]05
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.
Transmission complete // awaiting log
KEEP THE
STREAK ALIVE.
Dossier 34 of 127 decoded in the Data Structures & Algorithms track. One more won't hurt.