Skip to main content

16. Add Two Numbers

mediumAsked at Coursera

Add two numbers represented as reversed linked lists, a carry-propagation problem Coursera uses to test pointer manipulation and edge-case handling.

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, and each node contains a single digit. Add the two numbers and return the sum as a linked list in the same reversed format.

Constraints

  • Number of nodes in each list is in the range [1, 100]
  • 0 <= Node.val <= 9
  • The lists represent numbers that do not have leading zeros

Examples

Example 1

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

Example 2

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

Approaches

1. Convert to integers, add, re-encode

Extract both numbers, add them, then re-build the list — breaks on very large inputs beyond Number.MAX_SAFE_INTEGER.

Time
O(n)
Space
O(n)
// Unsafe for large inputs
function addTwoNumbers(l1, l2) {
  // convert, add, rebuild — skipped for brevity
}

Tradeoff:

2. Digit-by-digit with carry

Walk both lists simultaneously, summing digits and a carry variable. Use a dummy head to simplify list construction and handle the final carry after both lists are exhausted.

Time
O(max(m,n))
Space
O(max(m,n))
function addTwoNumbers(l1, l2) {
  const dummy = new ListNode(0);
  let cur = dummy, carry = 0;
  while (l1 || l2 || carry) {
    const sum = (l1 ? l1.val : 0) + (l2 ? l2.val : 0) + carry;
    carry = Math.floor(sum / 10);
    cur.next = new ListNode(sum % 10);
    cur = cur.next;
    if (l1) l1 = l1.next;
    if (l2) l2 = l2.next;
  }
  return dummy.next;
}

Tradeoff:

Coursera-specific tips

Coursera interviews emphasize algorithms for educational platforms, content recommendation systems, and scalable delivery pipelines. Medium-difficulty graph and DP problems are typical.

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

Practice these live with InterviewChamp.AI →