InterviewPrepKit

Home / Coding / Linked List

Add Two Numbers

medium Original ↗
Solving tips
  • Digits are stored least-significant-first, which is exactly the order grade-school column addition runs, so simulate it directly instead of converting to an integer.
  • Use a dummy head to build the result, keep a single carry, and emit (d1 + d2 + carry) % 10 with divmod each step; treat a missing node as 0.
  • The loop condition must be 'while l1 or l2 or carry': stopping at 'l1 and l2' truncates and 'l1 or l2' drops a final carry (999 + 1 fails).
  • Target O(max(n, m)) time, O(1) extra space; advance each list pointer only when it is non-None to avoid None.next.

Problem

Two non-negative integers are stored in two singly linked lists, one digit per node, with the least significant digit first. Add the two numbers and return the sum as a linked list in the same reversed-digit format.

Neither number has leading zeros, except the number 0 itself (a single 0 node).

Examples

  • Input: l1 = 2 -> 4 -> 3, l2 = 5 -> 6 -> 4 → Output: 7 -> 0 -> 8 The lists encode 342 and 465; 342 + 465 = 807, stored as 7,0,8.
  • Input: l1 = 0, l2 = 0 → Output: 0 0 + 0 = 0.
  • Input: l1 = 9 -> 9 -> 9, l2 = 1 → Output: 0 -> 0 -> 0 -> 1 999 + 1 = 1000 — the carry ripples through and creates a new most-significant digit.

Constraints

  • Each list has [1, 100] nodes.
  • 0 <= Node.val <= 9
  • No leading zeros (other than the number 0).

Think about it first

Hint 1 Least-significant-digit-first is a gift: both lists already start at the digit where grade-school addition starts.
Hint 2 Walk both lists together. At each position the output digit is (d1 + d2 + carry) % 10 and the new carry is the integer quotient by 10. What happens when one list is shorter?
Hint 3 Loop while either list has nodes or the carry is nonzero, treating a missing node as digit 0. A dummy head keeps the list-building clean. One pass, no number conversion needed.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.