Skip to main content

31. Add Two Numbers

mediumAsked at Ola

Add two numbers represented as linked lists in reverse-digit order.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each node contains a single digit. Add the two numbers and return the sum as a linked list.

Constraints

  • 1 <= number of nodes <= 100
  • 0 <= Node.val <= 9
  • It is guaranteed the lists have no leading zeros except 0 itself

Examples

Example 1

Input
l1 = [2,4,3], l2 = [5,6,4]
Output
[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]

Approaches

1. Convert via BigInt

Reconstruct integers from each list, add via BigInt, then split back.

Time
O(n+m)
Space
O(n+m)
const toNum = n => { let s='', cur=n; while(cur){ s = cur.val + s; cur=cur.next; } return BigInt(s); };
const sum = (toNum(l1) + toNum(l2)).toString();
// build list from sum reversed

Tradeoff:

2. Single pass with carry

Walk both lists with a carry digit; allocate a new sum node each step.

Time
O(n+m)
Space
O(n+m)
function addTwoNumbers(l1, l2) {
  const dummy = { next: null };
  let tail = dummy, carry = 0;
  while (l1 || l2 || carry) {
    const s = (l1?.val||0) + (l2?.val||0) + carry;
    carry = Math.floor(s / 10);
    tail.next = { val: s % 10, next: null };
    tail = tail.next;
    l1 = l1?.next;
    l2 = l2?.next;
  }
  return dummy.next;
}

Tradeoff:

Ola-specific tips

Ola checks if you handle differing list lengths and trailing carry; relate it to merging multi-digit usage counters from two driver shards.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Add Two Numbers and other Ola interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →