CodeArchon

mediumLinked ListAmazonMicrosoftApple

Digit Chain Sum

Two very large non-negative integers are stored one digit per node, least-significant digit first. Produce their sum in the same format.

Given two linked lists `a` and `b` of digits (LSB first), return a linked list of the sum.

Choose approach

2
a
4
3
5
b
6
4
nil
1/5
Narrationstep 1 of 5

Digits are stored least-significant first → walk both chains in lockstep, add digits + carry.

1def digit_chain_sum(a, b):
2 dummy = ListNode(0)
3 tail = dummy
4 carry = 0
5 while a or b or carry:
6 s = (a.val if a else 0) + (b.val if b else 0) + carry
7 carry, d = divmod(s, 10)
8 tail.next = ListNode(d)
9 tail = tail.next
10 a = a.next if a else None
11 b = b.next if b else None
12 return dummy.next
Variables
aLen=3
bLen=3

How to think about it

  1. LSB-first makes addition easy: no need to align from the right.
  2. A dummy head simplifies the first append.
  3. Loop while any input remains OR carry is non-zero.
  4. Terminating carry → one extra MSB node.

Edge cases to catch in interview

  • Unequal lengths — treat missing digits as 0.
  • Final carry becomes an extra MSB.
  • Either list empty → the other (possibly with carry).

Examples

Example 1[7,0,8]
{"aVals":[2,4,3],"bVals":[5,6,4]}

342 + 465 = 807.

Example 2[8,9,9,9,0,0,0,1]
{"aVals":[9,9,9,9,9,9,9],"bVals":[9,9,9,9]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed