16. Add Two Numbers
mediumAsked at CourseraAdd two numbers represented as reversed linked lists, a carry-propagation problem Coursera uses to test pointer manipulation and edge-case handling.
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 in the same reversed format.
Constraints
Number of nodes in each list is in the range [1, 100]0 <= Node.val <= 9The lists represent numbers that do not have leading zeros
Examples
Example 1
l1 = [2,4,3], l2 = [5,6,4][7,0,8]Example 2
l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9][8,9,9,9,0,0,0,1]Approaches
1. Convert to integers, add, re-encode
Extract both numbers, add them, then re-build the list — breaks on very large inputs beyond Number.MAX_SAFE_INTEGER.
- Time
- O(n)
- Space
- O(n)
// Unsafe for large inputs
function addTwoNumbers(l1, l2) {
// convert, add, rebuild — skipped for brevity
}Tradeoff:
2. Digit-by-digit with carry
Walk both lists simultaneously, summing digits and a carry variable. Use a dummy head to simplify list construction and handle the final carry after both lists are exhausted.
- Time
- O(max(m,n))
- Space
- O(max(m,n))
function addTwoNumbers(l1, l2) {
const dummy = new ListNode(0);
let cur = dummy, carry = 0;
while (l1 || l2 || carry) {
const sum = (l1 ? l1.val : 0) + (l2 ? l2.val : 0) + carry;
carry = Math.floor(sum / 10);
cur.next = new ListNode(sum % 10);
cur = cur.next;
if (l1) l1 = l1.next;
if (l2) l2 = l2.next;
}
return dummy.next;
}Tradeoff:
Coursera-specific tips
Coursera interviews emphasize algorithms for educational platforms, content recommendation systems, and scalable delivery pipelines. Medium-difficulty graph and DP problems are typical.
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 Coursera interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →