Add Two Numbers
You are given two non-empty linked lists representing two non-negative integers stored in reverse order. Each node contains a single digit. Add the two numbers and return the sum as a linked list.
Example: Input: l1 = [2,4,3], l2 = [5,6,4] → Output: [7,0,8] (342 + 465 = 807)
Sample Input
—
Sample Output
—
Constraints
- Each linked list has 1 to 100 nodes
- 0 <= Node.val <= 9
- Numbers do not have leading zeros
Test Cases
Case 1
Args: [[2,4,3],[5,6,4]]
Expected: [7,0,8]
Case 2
Args: [[0],[0]]
Expected: [0]
Topics
Elementary Math with Carry
Traverse both lists simultaneously, summing digits with carry.
function addTwoNumbers(l1, l2) {
let dummy = {val: 0, next: null}, curr = dummy, carry = 0;
while (l1 || l2 || carry) {
let sum = carry + (l1 ? l1.val : 0) + (l2 ? l2.val : 0);
carry = Math.floor(sum / 10);
curr.next = {val: sum % 10, next: null};
curr = curr.next;
if (l1) l1 = l1.next;
if (l2) l2 = l2.next;
}
return dummy.next;
}
Time: O(max(m, n)) | Space: O(max(m, n))
Saved in this browser only. Private to you.