Skip to main content

11. Add Two Numbers

mediumAsked at Swiggy

Add two numbers stored as digits in linked lists in reverse order.

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

Problem

Two non-empty linked lists each represent a non-negative integer; digits are stored in reverse order, one digit per node. Add the two numbers and return the sum as a new linked list in the same format.

Constraints

  • 1 <= nodes per 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] (342+465=807)

Example 2

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

Approaches

1. Convert to BigInt

Reassemble both numbers, add, split back into digits.

Time
O(n)
Space
O(n)
function num(l){let s='';for(;l;l=l.next)s=l.val+s;return BigInt(s);}
let sum=(num(l1)+num(l2)).toString();
let head=null;
for (const c of sum) head={val:+c,next:head};
return head;

Tradeoff:

2. Single pass with carry

Walk both lists in lockstep, summing digits plus carry into new nodes. Continue while either list has nodes or the carry is non-zero.

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

Tradeoff:

Swiggy-specific tips

Swiggy weighs your handling of the trailing carry edge case heavily; missing the while-carry loop is the fastest way to fail their real-time payment-rounding analogue.

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

Practice these live with InterviewChamp.AI →