Skip to main content

13. Add Two Numbers

mediumAsked at Gojek

Add two non-negative integers stored as linked lists in reverse digit order and return the sum as a list.

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

Problem

You are given two non-empty linked lists representing two non-negative integers. Each node contains a single digit and the digits are stored in reverse order. Add the two numbers and return the sum as a linked list.

Constraints

  • The number of nodes is in [1, 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], l2 = [1]
Output
[0,0,1]

Approaches

1. Convert to number

Materialize each list as an integer, add, then rebuild the list.

Time
O(n)
Space
O(n)
const toN = l => { let s = '', n = l; while (n) { s = n.val + s; n = n.next; } return BigInt(s); };
const sum = String(toN(l1) + toN(l2)).split('').reverse();
// build list from sum

Tradeoff:

2. Digit-by-digit with carry

Walk both lists together summing values plus a carry, appending a node per digit. Continue while any list or the carry remains.

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

Tradeoff:

Gojek-specific tips

Gojek runs ledgers across SEA currencies where digit overflow in JS Number is a real bug, so showing you avoid converting to Number scores trust signal for a payments codebase.

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

Practice these live with InterviewChamp.AI →