Add Two Numbers II - Problem

Imagine you have two large numbers written on paper, but instead of storing them as regular integers, each digit is stored in a separate box (node) of a linked list. The twist? The most significant digit comes first - just like how we normally write numbers!

You're given two non-empty linked lists representing two non-negative integers. Each node contains a single digit (0-9), and you need to add these two numbers together and return the sum as a new linked list.

For example:

  • Number 1: 7 → 2 → 4 → 3 represents 7243
  • Number 2: 5 → 6 → 4 represents 564
  • Sum: 7 → 8 → 0 → 7 represents 7807

The challenge is that we can't simply reverse the lists (like in Add Two Numbers I) because we need to maintain the original structure. We need to handle carries that propagate from right to left, just like elementary school addition!

Input & Output

example_1.py — Basic Addition
$ Input: l1 = [7,2,4,3], l2 = [5,6,4]
Output: [7,8,0,7]
💡 Note: 7243 + 564 = 7807. The digits are stored with most significant digit first.
example_2.py — Addition with Carry
$ Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [8,0,7]
💡 Note: 243 + 564 = 807. Notice how the carry propagates from right to left.
example_3.py — Single Digits
$ Input: l1 = [0], l2 = [0]
Output: [0]
💡 Note: 0 + 0 = 0. Edge case with single zero digits.

Constraints

  • The number of nodes in each linked list is in the range [1, 100]
  • 0 ≤ Node.val ≤ 9
  • The input represents a valid number without leading zeros
  • Follow up: Could you solve it without reversing the input lists?

Visualization

Tap to expand
Add Two Numbers II - Linked List Addition INPUT L1 (Most Significant First): 7 2 4 3 L2 (Most Significant First): 5 6 4 Represents: 7243 + 564 l1 = [7, 2, 4, 3] l2 = [5, 6, 4] Different lengths! Challenge: Carry propagates right to left (backwards) ALGORITHM STEPS 1 Use Two Stacks Push all nodes to stacks 3 4 2 7 Stack1 4 6 5 Stack2 2 Pop and Add Pop from both, add digits 3 Handle Carry carry = sum / 10 3+4=7, 4+6=10, 2+5+1=8 7+0+0=7 Carry: 0, 1, 0, 0 4 Build Result Prepend nodes to head Result builds right-to-left FINAL RESULT Result Linked List: 7 8 0 7 Output: [7, 8, 0, 7] Verification: 7243 + 564 = 7807 OK - Correct! Time: O(max(m,n)) Space: O(m+n) for stacks Key Insight: Using stacks reverses the digit order naturally, allowing us to add from least significant digit to most significant digit (right to left) without modifying the original linked lists. The carry propagates correctly as we pop elements, and we build the result by prepending new nodes. TutorialsPoint - Add Two Numbers II | Optimal Solution (Stack-based)
Asked in
Amazon 45 Microsoft 38 Apple 32 Google 28
68.0K Views
High Frequency
~18 min Avg. Time
1.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