Skip to main content

11. Add Two Numbers

mediumAsked at Freshworks

Add two big numbers stored as reverse-order linked lists — Freshworks frames it as merging two automation-rule counters that overflow Int32.

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

Problem

You are given two non-empty linked lists representing two non-negative integers, stored in reverse order, one digit per node. Add the two numbers and return the sum as a linked list, also in reverse order.

Constraints

  • 1 <= each list length <= 100
  • 0 <= Node.val <= 9
  • Neither list has leading zeros except the number 0

Examples

Example 1

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

Explanation: 342 + 465 = 807

Example 2

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

Approaches

1. Brute force (convert to numbers)

Walk both lists, build JS numbers, add, then build a result list. Fails for >15 digits because of float precision.

Time
O(n+m)
Space
O(n+m)
let a=0n, b=0n, p=1n; let c=l1; while(c){a+=BigInt(c.val)*p;p*=10n;c=c.next;}
// ...same for l2, then build list from a+b

Tradeoff:

2. Single pass with carry

Walk both lists in lockstep, sum digit + digit + carry, push the units digit, propagate carry. Handles unequal lengths and a trailing carry.

Time
O(max(n,m))
Space
O(max(n,m))
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 s = a + b + carry;
    carry = Math.floor(s / 10);
    tail.next = { val: s % 10, next: null };
    tail = tail.next;
    if (l1) l1 = l1.next;
    if (l2) l2 = l2.next;
  }
  return dummy.next;
}

Tradeoff:

Freshworks-specific tips

Freshworks specifically watches for the trailing-carry case (sum spills a new most-significant digit) — drive an example like [9] + [1] = [0,1] before submitting.

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

Practice these live with InterviewChamp.AI →