Add Two Numbers II Medium 0 attempts
LeetCode ↗

Add Two Numbers II

Medium Linked List LeetCode

Given two non-empty linked lists representing two non-negative integers where the most significant digit comes first, add them and return the sum as a linked list.

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

Sample Input
Sample Output
Constraints
  • 1 to 100 nodes per list
  • 0 <= Node.val <= 9
  • Numbers have no leading zeros
Test Cases
Case 1
Args: [[7,2,4,3],[5,6,4]] Expected: [7,8,0,7]
Topics

Stack-Based Addition

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

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)

Saved in this browser only. Private to you.

JavaScript