Skip to main content

14. Add Two Numbers

mediumAsked at SoFi

Add two numbers represented by linked lists in reverse order — SoFi loves this because manual carry propagation is identical to multi-period loan amortization with monthly carry-overs.

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 range [1, 100]
  • 0 <= Node.val <= 9
  • Numbers do not contain leading zeros except for 0 itself

Examples

Example 1

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

Example 2

Input
l1 = [0], l2 = [0]
Output
[0]

Approaches

1. Convert to integers

Read both linked lists to arrays, parse as integers, add, then write digits back — fails on big numbers.

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

Tradeoff:

2. Digit-by-digit with carry

Walk both lists simultaneously, summing digits plus carry, allocating a new node for each digit. Continue while either list has nodes or carry remains.

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 sum = (l1?.val || 0) + (l2?.val || 0) + carry;
    carry = Math.floor(sum / 10);
    cur.next = { val: sum % 10, next: null };
    cur = cur.next;
    l1 = l1?.next;
    l2 = l2?.next;
  }
  return dummy.next;
}

Tradeoff:

SoFi-specific tips

SoFi specifically grades for carry-propagation correctness — interest accrual carries cents between billing periods, and a one-cent rounding error in production = compliance headache.

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

Practice these live with InterviewChamp.AI →