14. Add Two Numbers
mediumAsked at MercadoLibreSum two integers represented as reverse-order linked lists, digit by digit.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Two non-empty linked lists represent two non-negative integers with digits stored in reverse order. Add the two numbers and return the sum as a linked list in the same reverse order.
Constraints
1 <= node count <= 1000 <= Node.val <= 9No leading zeros except the number 0
Examples
Example 1
l1 = [2,4,3], l2 = [5,6,4][7,0,8]Example 2
l1 = [9,9,9], l2 = [1][0,0,0,1]Approaches
1. Convert to bigints
Read both lists into BigInts, sum, then rebuild a list. Fragile on huge sizes and overkill.
- 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);
// rebuild list from sum.toString()...Tradeoff:
2. Digit-wise with carry
Walk both lists in lockstep, sum digits with a carry, and append each new digit to a result list.
- Time
- O(max(m,n))
- Space
- O(max(m,n))
function addTwoNumbers(l1, l2) {
const dummy = { next: null };
let cur = dummy, carry = 0;
while (l1 || l2 || carry) {
const v = (l1?.val || 0) + (l2?.val || 0) + carry;
carry = (v / 10) | 0;
cur.next = { val: v % 10, next: null };
cur = cur.next;
l1 = l1?.next; l2 = l2?.next;
}
return dummy.next;
}Tradeoff:
MercadoLibre-specific tips
Mercado Pago ledger engineers want clean carry handling because their multi-currency settlement service adds digits across millions of low-value pesos and centavos transactions every minute.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Add Two Numbers and other MercadoLibre interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →