2/670

2. Add Two Numbers

Medium

You are given two non-negative integers represented as digit lists l1 and l2. In each list the digits are stored in reverse order, the least-significant digit comes first, and there are no leading zeros except for the number 0 itself, which is the single-element list [0].

Add the two numbers and return the sum the same way: a list of its digits in reverse order (least-significant first).

For example l1 = [2, 4, 3] represents 342 and l2 = [5, 6, 4] represents 465, their sum 807 is returned as [7, 0, 8]. Remember to carry across positions, and note the sum may be one digit longer than either input.

Example 1: 342 + 465 = 807, digits stored least-significant firstEach node holds one digit; because the lists are reversed, the front digits are the ones place and line up for column addition.
l1243= 342l2564= 465sum708= 807least-significantdigit first

Example 1:

Input: l1 = [2, 4, 3], l2 = [5, 6, 4]

Output: [7, 0, 8]

Explanation: 342 + 465 = 807, whose digits in reverse order are 7, 0, 8.

Example 2:

Input: l1 = [9, 9, 9, 9, 9, 9, 9], l2 = [9, 9, 9, 9]

Output: [8, 9, 9, 9, 0, 0, 0, 1]

Explanation: 9999999 + 9999 = 10009998, whose digits reversed are 8, 9, 9, 9, 0, 0, 0, 1.

Constraints:

  • The number of digits in each list is between 1 and 100.
  • Each digit is between 0 and 9.
  • Neither number has leading zeros, except the number 0 itself (represented as [0]).

Hints:

The digits are already least-significant first, so you can add the lists from index 0 forward, exactly like adding by hand.

Carry the tens digit into the next position, and keep looping while a non-zero carry remains even after both lists end, that is what adds the new leading digit in cases like 99 + 1.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: l1 = [2, 4, 3], l2 = [5, 6, 4]

Expected output: [7, 0, 8]