Add Two Numbers Medium 0 attempts
LeetCode ↗

Add Two Numbers

Medium Linked List LeetCode

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.

Input Format
Implement addTwoNumbers(l1, l2). Inputs below show JavaScript function arguments; there is no stdin parsing. Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.
Output Format
Return the result described in the statement. Returned list heads are displayed as value arrays; a null head is [].

Sample Input and Output

Example 1 · Run Sample

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

Example 2

Input
l1 = [0]
l2 = [0]
Output
[0]
Constraints
  • Each linked list has 1 to 100 nodes
  • 0 <= Node.val <= 9
  • Numbers do not have leading zeros
Test Cases (2)
Case 1
Args: [[2,4,3],[5,6,4]] Expected: [7,0,8]
Case 2
Args: [[0],[0]] Expected: [0]
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))

Saved in this browser only. Private to you.

JavaScript