Skip to main content

14. Add Two Numbers

mediumAsked at Wise

Sum two integers represented as digit linked lists with carry propagation — Wise uses this as the canonical money-math probe (no floats, ever).

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 with one digit per node. Add the two numbers and return the sum as a linked list.

Constraints

  • 1 <= nodes in each list <= 100
  • 0 <= Node.val <= 9
  • No 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. Parse to Number then split back

Read each list into a JS Number, add, write digits back. Breaks on large lists.

Time
O(n)
Space
O(n)
function toNum(l){ let n=0,p=1; while(l){ n+=l.val*p; p*=10; l=l.next; } return n; }
let sum=toNum(l1)+toNum(l2);
const head={val:0,next:null}; let t=head;
do { t.next={val:sum%10,next:null}; t=t.next; sum=Math.floor(sum/10); } while(sum>0);
return head.next;

Tradeoff:

2. Digit-by-digit with carry

Walk both lists in lockstep keeping a carry; allocate a new node per pair. Handles arbitrary length and never overflows.

Time
O(max(m,n))
Space
O(max(m,n))
function addTwoNumbers(l1, l2){
  const dummy = { val: 0, next: null };
  let tail = 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 = sum >= 10 ? 1 : 0;
    tail.next = { val: sum % 10, next: null };
    tail = tail.next;
    if (l1) l1 = l1.next;
    if (l2) l2 = l2.next;
  }
  return dummy.next;
}

Tradeoff:

Wise-specific tips

Wise interviewers will fail you fast if you reach for Number — they want the carry-propagation pattern because that is exactly how their money math is implemented (integer minor-units, never floats).

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

Practice these live with InterviewChamp.AI →