Skip to problem
←

Add Two Numbers

Medium 0 attempts

You're given two non-empty linked lists, l1 and l2, each representing a non-negative integer with its digits stored in reverse order — one digit per node, least significant digit first. Add the two numbers together and return the result as a linked list built the same way.

Function contract

Implement addTwoNumbers(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 least-significant-digit-first order. The runner displays its node values as an array.

Example 1

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

Example 2

Input
l1 = [0]
l2 = [0]
Output
[0]
Visual Aid
Least significant digit first
l1243342l2564465sum708807

342 + 465 = 807. The head stores the ones digit, so the result is 7 → 0 → 8.

Constraints
  • Each linked list has 1 to 100 nodes
  • 0 <= Node.val <= 9
  • Numbers do not have leading zeros
Topics

Elementary Math with Carry

Traverse both lists simultaneously, summing digits with carry.

javascript
function addTwoNumbers(l1, l2) {
  let dummy = {val: 0, next: null}, curr = dummy, carry = 0;
  while (l1 || l2 || carry) {
    let sum = carry + (l1 ? l1.val : 0) + (l2 ? l2.val : 0);
    carry = Math.floor(sum / 10);
    curr.next = {val: sum % 10, next: null};
    curr = curr.next;
    if (l1) l1 = l1.next;
    if (l2) l2 = l2.next;
  }
  return dummy.next;
}

Time: O(max(m, n)) | Space: O(max(m, n))

Loading discussion…

Saved in this browser only. Private to you.

JavaScript