14. Add Two Numbers
mediumAsked at GrabAdd two linked-list digits with carry — Grab uses this to test pointer + arithmetic handling in one shot.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
You are given two non-empty linked lists representing two non-negative integers, with digits stored in reverse order. Add the numbers and return the sum as a linked list.
Constraints
1 <= length of each list <= 1000 <= Node.val <= 9Numbers have no leading zeros except 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 integers
Read both lists into BigInt, add, then build the result list.
- Time
- O(n)
- Space
- O(n)
// fails on lists longer than 64 digits without BigInt
// brittle for partition shards across SEA regionsTradeoff:
2. Single-pass with carry
Walk both lists simultaneously, sum each digit pair plus carry, append a node per digit.
- 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 a = l1 ? l1.val : 0;
const b = l2 ? l2.val : 0;
const sum = a + b + carry;
carry = Math.floor(sum / 10);
cur.next = { val: sum % 10, next: null };
cur = cur.next;
if (l1) l1 = l1.next;
if (l2) l2 = l2.next;
}
return dummy.next;
}Tradeoff:
Grab-specific tips
Grab interviewers reward candidates who handle the carry loop cleanly — frame as adding partitioned wallet balances across regional shards.
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 Grab interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →