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.

Visualization

Tap to expand
Stack 13427Stack 2465ADDITION3 + 4 = 7carry = 07807Result: 7807Pop from stacksPrepend to result🎯 Key: Stacks reverse the order naturally, allowing right-to-left addition!
Understanding the Visualization
1
Load the Stacks
Push all digits from both numbers onto separate stacks, naturally reversing their order
2
Add from Right to Left
Pop digits from stacks and add them with any carry from the previous addition
3
Handle the Carry
If sum ≥ 10, carry the 1 to the next position and keep the remainder digit
4
Build Result List
Create new nodes and prepend them to build the final result list
Key Takeaway
🎯 Key Insight: Stacks naturally reverse the digit order, letting us perform elementary school addition (right-to-left) while keeping the original linked lists intact!

Time & Space Complexity

Time Complexity
⏱️
O(max(n, m))

Need to traverse both lists once to fill stacks, then process all digits once more

n
2n
Linear Growth
Space Complexity
O(n + m)

Space for two stacks to hold all digits from both lists

n
2n
Linearithmic Space

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?
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