Add Two Digit Chains

Medium · Linked Lists · about 30 min

A billing system stores very large amounts as linked lists of digits, most significant digit first: the amount 7243 is stored as 7 → 2 → 4 → 3. Amounts can have hundreds of digits, more than a normal number type can hold exactly.

Given two amounts as digit lists a and b, return their sum as a digit list, most significant digit first.

  • Each list has at least one digit, every digit is 0 to 9, and there are no leading zeros (zero itself is [0]).
  • The answer has no leading zeros either.

Example: add_digit_chains([7, 2, 4, 3], [5, 6, 4]) → [7, 8, 0, 7] (7243 + 564 = 7807)

Hints

  • You add from the ones digit, which is at the end of each chain. Reversing a chain is a standard three-pointer walk.
  • Keep looping while either chain still has a node or there is still a carry. A missing digit counts as 0.
  • Put each new digit in front of the answer chain, so the answer ends up most significant digit first without another reverse.

Learn the pattern first: the Linked Lists lesson.

More Linked Lists problems