Skip to problem
←

Add Two Numbers II

Medium 0 attempts

You're given two non-empty linked lists l1 and l2 that each represent a non-negative integer, but this time with the most significant digit stored first. Add the two numbers and return the sum as a linked list in the same most-significant-digit-first order.

Function contract

Implement addTwoNumbersII(l1, l2). Arguments are linked-list heads with val and next fields; the examples display their node values as arrays.

Output: The head of a new linked list containing the sum in most-significant-digit-first order. The runner displays its node values as an array.

Example 1

Input
l1 = [7,2,4,3]
l2 = [5,6,4]
Output
[7,8,0,7]

Example 2

Input
l1 = [9,9]
l2 = [1]
Output
[1,0,0]
Visual Aid
Most significant digit first
l172437243l2564564sum78077807

7243 + 564 = 7807. Read each list from head to tail.

Constraints
  • 1 to 100 nodes per list
  • 0 <= Node.val <= 9
  • Numbers have no leading zeros
Topics

Stack-Based Addition

Use stacks to reverse the digit order, then add with carry.

javascript
function addTwoNumbersII(l1, l2) {
  let s1 = [], s2 = [];
  while (l1) { s1.push(l1.val); l1 = l1.next; }
  while (l2) { s2.push(l2.val); l2 = l2.next; }
  let carry = 0, head = null;
  while (s1.length || s2.length || carry) {
    let sum = carry + (s1.pop() || 0) + (s2.pop() || 0);
    carry = Math.floor(sum / 10);
    let node = {val: sum % 10, next: head};
    head = node;
  }
  return head;
}

Time: O(m + n) | Space: O(m + n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript