Skip to main content

16. Add Two Numbers

mediumAsked at Udemy

Sum two numbers represented as reversed linked lists — Udemy uses this to probe carry propagation logic common in payment and pricing calculations.

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.

Constraints

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

Approaches

1. Brute force

Convert lists to integers, add them, then rebuild list — breaks for very long lists due to integer overflow.

Time
O(n)
Space
O(n)
// convert to BigInt, add, re-encode
// not viable for interview; digits can exceed safe integer range

Tradeoff:

2. In-place carry simulation

Traverse both lists together, summing digits plus carry at each step, creating a new node per digit and propagating any leftover carry at the end.

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:

Udemy-specific tips

Udemy asks about e-learning recommendation systems, content search, and marketplace algorithms — balanced mix of arrays, hash maps, and dynamic programming problems.

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

Practice these live with InterviewChamp.AI →