Problem 227572 · medium · Level 02 Linear Data Structures

Adding Numbers Kept on Digit Wheels

linked list · arithmetic · carry

An old adding machine keeps every number on a chain of digit wheels, modelled here as a singly linked list of decimal digits with the units digit first: the chain 3 -> 7 -> 2 stands for 273. Given the heads a and b of two chains holding non-negative numbers, build and return a new chain in the same format that holds their sum. An empty chain stands for 0.

Examples

Input:  a = 3 -> 7 -> 2, b = 8 -> 5 -> 1
Output: 1 -> 3 -> 4
Explanation: 273 + 158 = 431

Input:  a = 9 -> 9, b = 1
Output: 0 -> 0 -> 1
Explanation: 99 + 1 = 100

Constraints

  • 0 <= len(a), len(b) <= 10**4, at least one list is non-empty
  • Each value is a digit 0..9; there are no leading zeros except the number 0 itself
  • Target: O(max(len(a), len(b))) time; do not convert the whole number to a Python int

Goals

  • Walk two lists of different lengths together
  • Propagate a carry, including a final extra digit
Starting Python…