Add Two Numbers - Problem

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input & Output

Example 1 — Basic Addition
$ Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
💡 Note: 342 + 465 = 807. The digits are stored in reverse order, so [2,4,3] represents 342, [5,6,4] represents 465, and the sum 807 is returned as [7,0,8].
Example 2 — Different Lengths
$ Input: l1 = [0], l2 = [0]
Output: [0]
💡 Note: 0 + 0 = 0. The simplest case where both numbers are zero.
Example 3 — Carry Propagation
$ Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
💡 Note: 9999999 + 9999 = 10009998. Shows how carries propagate through multiple digits, resulting in a longer output list.

Constraints

  • The number of nodes in each linked list is in the range [1, 100]
  • 0 ≤ Node.val ≤ 9
  • It is guaranteed that the list represents a number that does not have leading zeros

Visualization

Tap to expand
Add Two Numbers - Linked List Addition INPUT l1 (represents 342) 2 4 3 null l2 (represents 465) 5 6 4 null Input Values: l1 = [2,4,3] l2 = [5,6,4] Digits stored in reverse 342 + 465 = 807 ALGORITHM STEPS 1 Initialize Create dummy head, carry=0 2 Add Digits + Carry sum = val1 + val2 + carry 3 Extract Digit digit = sum % 10 4 Update Carry carry = sum / 10 Single Pass Iterations: i l1 l2 sum digit carry 1 2 5 7 7 0 2 4 6 10 0 1 3 3 4 8 8 0 FINAL RESULT Result: [7,0,8] (represents 807) 7 0 8 null Verification: 342 + 465 807 Output: [7, 0, 8] OK - Sum computed correctly! Key Insight: The reverse storage of digits is actually advantageous! We can add digits from left to right in the linked lists, which corresponds to adding from ones place to higher places - exactly how manual addition works. Track the carry and propagate it to the next digit. Time: O(max(m,n)), Space: O(1) TutorialsPoint - Add Two Numbers | Single Pass with Carry Approach
Asked in
Amazon 85 Microsoft 72 Google 68 Facebook 45
666.0K Views
Very High Frequency
~25 min Avg. Time
18.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen