Skip to main content

14. Add Two Numbers

mediumAsked at Squarespace

Add two non-negative integers represented as reversed linked lists and return the sum as a linked list; Squarespace uses it to test careful carry handling on a list scan.

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

Problem

Two non-empty linked lists store non-negative integers in reverse order, one digit per node. Add the numbers and return the sum as a linked list in the same reverse-order form.

Constraints

  • Lists hold 1 to 100 digits
  • Each node value is 0-9
  • Neither input number has 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=[0], l2=[0]
Output
[0]

Approaches

1. Convert, add, rebuild

Convert each list to a number, add, then split the digits back. Fails for very large lists due to integer overflow in JS.

Time
O(n)
Space
O(n)
const toNum=l=>{let s='',n=l; while(n){s=n.val+s;n=n.next;} return BigInt(s);};
const sum=(toNum(l1)+toNum(l2)).toString();
let dummy={next:null},cur=dummy;
for(const c of sum.split('').reverse()){ cur.next={val:+c,next:null}; cur=cur.next; }
return dummy.next;

Tradeoff:

2. Digit-by-digit with carry

Walk both lists in lockstep, summing digits plus carry, emitting a new node each step. Handles arbitrary lengths cleanly.

Time
O(n)
Space
O(n)
function addTwoNumbers(l1, l2) {
  const dummy = { val: 0, next: null };
  let cur = dummy, carry = 0;
  while (l1 || l2 || carry) {
    const a = l1 ? l1.val : 0, 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 dummy.next;
}

Tradeoff:

Squarespace-specific tips

Squarespace evaluators want you to surface the final carry-only iteration and to relate it to their analytics rollup, which carries overflow from per-minute to per-hour buckets.

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

Practice these live with InterviewChamp.AI →