Add Two Numbers
Difficulty: Medium
Two non-negative integers are stored as linked lists, one digit per node, least significant digit first (so [2, 4, 3] is 342). Add them and return the sum as a linked list in the same order.
Neither list has leading zeros, except the number 0 itself, which is a single node holding 0.
Examples
Input: l1 = [2, 4, 3], l2 = [5, 6, 4]
Output: [7, 0, 8]
342 + 465 = 807, and 807 written least-significant-digit-first is [7, 0, 8].
Input: l1 = [0], l2 = [0]
Output: [0]
Input: l1 = [9, 9], l2 = [1]
Output: [0, 0, 1]
99 + 1 = 100, and the carry has to ripple through two extra digits.
Constraints
Each list has between 1 and 100 nodes.
0 <= Node.val <= 9
Neither list has a leading zero, except the number 0 itself.
Approach
You could convert each list into a (possibly very large) number, add them, and turn the result back into a list. That works, but the conversions are more work than needed.
The direct approach adds the way you do by hand. Walk both lists together, one digit at a time. Add the two digits plus the carry, write down the ones digit, and carry the rest. If a carry is left after both lists end, it becomes one final digit.
Solutions
Brute Force — Convert to Numbers and Back
Read each list into a BigInt (so long lists don't lose precision), add them, then split the sum into a new list, least significant digit first.
class ListNode {
constructor(val, next = null) {
this.val = val;
this.next = next;
}
}
function addTwoNumbers(l1, l2) {
function listToBigInt(node) {
let digits = "";
while (node) {
digits = String(node.val) + digits; // most significant digit ends up first
node = node.next;
}
return BigInt(digits);
}
const sum = listToBigInt(l1) + listToBigInt(l2);
const digits = sum.toString().split("").reverse(); // back to least-significant-first
const dummy = new ListNode(0);
let curr = dummy;
for (const digit of digits) {
curr.next = new ListNode(Number(digit));
curr = curr.next;
}
return dummy.next;
}Time: O(n + m) — but with extra overhead building and parsing big-integer strings · Space: O(n + m)
Optimal — Digit-by-Digit Simulation
Walk both lists together. At each step, add the available digits (a finished list counts as 0) plus the carry. The new node's value is sum mod 10, and the new carry is sum divided by 10, rounded down. Continue while either list has nodes or a carry is left.
class ListNode {
constructor(val, next = null) {
this.val = val;
this.next = next;
}
}
function addTwoNumbers(l1, l2) {
const dummy = new ListNode(0);
let curr = dummy;
let carry = 0;
while (l1 !== null || l2 !== null || carry !== 0) {
const digit1 = l1 ? l1.val : 0;
const digit2 = l2 ? l2.val : 0;
const sum = digit1 + digit2 + carry;
carry = Math.floor(sum / 10);
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (l1) l1 = l1.next;
if (l2) l2 = l2.next;
}
return dummy.next;
}Time: O(max(n, m)) · Space: O(1) extra, not counting the output list