12. Add Two Numbers
mediumAsked at KlarnaAdd two non-negative integers represented as reversed linked lists, digit per node.
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 <= node count <= 1000 <= Node.val <= 9No leading zeros except the number 0 itself
Examples
Example 1
l1 = [2,4,3], l2 = [5,6,4][7,0,8]Example 2
l1 = [0], l2 = [0][0]Approaches
1. Convert to BigInt, add, rebuild
Read both lists into BigInt, add, then write digits back out.
- Time
- O(n)
- Space
- O(n)
function addTwoNumbers(l1, l2) {
const toBig = (l) => { let s = '', c = l; while (c) { s = c.val + s; c = c.next; } return BigInt(s); };
let sum = (toBig(l1) + toBig(l2)).toString();
const dummy = { next: null };
let tail = dummy;
for (const d of sum) { tail = tail.next = { val: +d, next: null }; }
// reverse...
return dummy.next;
}Tradeoff:
2. Single-pass digit-by-digit add
Walk both lists together, tracking a carry digit. The reversed encoding means least-significant digit is first, so addition flows naturally without reversing anything.
- Time
- O(max(m,n))
- Space
- O(max(m,n))
function addTwoNumbers(l1, l2) {
const dummy = { val: 0, next: null };
let tail = dummy, carry = 0;
while (l1 || l2 || carry) {
const a = l1 ? l1.val : 0;
const b = l2 ? l2.val : 0;
const sum = a + b + carry;
carry = Math.floor(sum / 10);
tail.next = { val: sum % 10, next: null };
tail = tail.next;
if (l1) l1 = l1.next;
if (l2) l2 = l2.next;
}
return dummy.next;
}Tradeoff:
Klarna-specific tips
Klarna treats this as a stand-in for cross-currency installment-ledger arithmetic; they will probe whether you handle the trailing carry and never silently truncate cents.
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 Klarna interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →