Skip to main content

10. Add Two Numbers

mediumAsked at Postman

Add two numbers represented by linked lists in reverse-digit order.

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 them and return the sum as a linked list, also in reverse order.

Constraints

  • List length is in [1, 100]
  • 0 <= node.val <= 9
  • No leading zeros except 0 itself

Examples

Example 1

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

Example 2

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

Approaches

1. Stringify and add

Read both lists into strings, reverse, parse as BigInt, add, then split into a list again.

Time
O(n)
Space
O(n)
// reverse both, BigInt(a)+BigInt(b), split digits back
// brittle and ignores the digit-by-digit lesson

Tradeoff:

2. Digit-by-digit with carry

Walk both lists together, summing digit + carry into a new node, advancing each pointer when present.

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

Tradeoff:

Postman-specific tips

Postman cares about the carry-loop pattern because chunked HTTP body assembly does the same: stream digits/bytes, keep a running residual, never load the whole payload.

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

Practice these live with InterviewChamp.AI →