Skip to main content

13. Add Two Numbers

mediumAsked at Ramp

Add two numbers whose digits are stored in reverse-order linked lists.

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

  • Number of nodes in each list is in the range [1, 100]
  • 0 <= Node.val <= 9
  • Neither list has leading zeros except the number 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], l2 = [9,9,9]
Output
[8,9,9,0,1]

Approaches

1. Brute force via integer reconstruction

Walk both lists into BigInts, add, split back into a linked list.

Time
O(n)
Space
O(n)
function addTwoNumbers(l1, l2) {
  const toBig = (n) => { let s = '', p = 10n ** 0n; while (n) { s = n.val + s; n = n.next; } return BigInt(s); };
  let sum = (toBig(l1) + toBig(l2)).toString().split('').reverse();
  let head = null;
  for (const d of sum) head = { val: +d, next: head };
  return reverse(head);
}

Tradeoff:

2. Single-pass carry

Walk both lists in lockstep, summing nodes with a carry; create a new node per digit.

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

Tradeoff:

Ramp-specific tips

Ramp pushes back on the BigInt-conversion shortcut because their corporate card rules engine processes money in minor units; the carry-propagation pattern signals you respect integer-precision boundaries.

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 Ramp interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →