Add Two Numbers
Detailed guide and Python implementation for the 'Add Two Numbers' problem.
1. Concept Overview
The 'Add Two Numbers' problem is a key challenge in the Linked List section.
This implementation focuses on easy-level logic in Python.
We prioritize technical accuracy and code readability in our provided solutions.
2. Real-World Applications
3. Visual Intuition
Visualizing the logic flow for Add Two Numbers.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Read the problem statement for Add Two Numbers carefully.
2. Formulate brute force
Draft a simple iterative solution.
3. Identify inefficiency
Look for redundant calculations.
4. Optimize search path
Use hashing or sorting to speed up the process.
5. Final Implementation
Clean up the code for production standards.
Problem Statement
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.
The linked lists are represented as Python lists. Implement a function addTwoNumbers(l1: list, l2: list) -> list that returns the sum as a list in reverse digit order.
- •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
Examples
[2,4,3], [5,6,4]
[7,0,8]
342 + 465 = 807. Represented in reverse: [7,0,8].
[0], [0]
[0]
0 + 0 = 0.
[9,9,9,9,9,9,9], [9,9,9,9]
[8,9,9,9,0,0,0,1]
9999999 + 9999 = 10009998. Represented in reverse: [8,9,9,9,0,0,0,1].
Need a Hint?
Edge Cases to Watch
- Empty input structures
- Single element inputs
- Large numerical bounds
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Interview Insights & Variations
Complexity Analysis Breakdown
Why Time: Directly evaluates all possibilities.
Why Space: Uses standard local memory.
Why Time: Optimized paths reduce total operations.
Why Space: May trade memory for speed.
Optimized Solution Python Code
Optimized Solution Python Code
def add_two_numbers_opt(l1, l2):
if isinstance(l1, list):
node1 = build_linked_list(l1)
node2 = build_linked_list(l2)
res = add_two_numbers_opt_helper(node1, node2)
return linked_list_to_list(res)
return add_two_numbers_opt_helper(l1, l2)
def add_two_numbers_opt_helper(l1: ListNode, l2: ListNode) -> ListNode:
dummy = ListNode(0)
curr = dummy
carry = 0
while l1 or l2 or carry:
val1 = l1.val if l1 else 0
val2 = l2.val if l2 else 0
total = val1 + val2 + carry
carry = total // 10
curr.next = ListNode(total % 10)
curr = curr.next
if l1: l1 = l1.next
if l2: l2 = l2.next
return dummy.nextBrute Force Code (Spoiler Guarded)
Brute Force Code (Spoiler Guarded)
def add_two_numbers_brute(l1, l2):
if isinstance(l1, list):
node1 = build_linked_list(l1)
node2 = build_linked_list(l2)
res = add_two_numbers_brute_helper(node1, node2)
return linked_list_to_list(res)
return add_two_numbers_brute_helper(l1, l2)
def add_two_numbers_brute_helper(l1: ListNode, l2: ListNode) -> ListNode:
def to_num(node):
num, place = 0, 1
while node:
num += node.val * place
place *= 10
node = node.next
return num
total = to_num(l1) + to_num(l2)
dummy = ListNode(0)
curr = dummy
for digit in str(total)[::-1]:
curr.next = ListNode(int(digit))
curr = curr.next
return dummy.next or ListNode(0)Algorithm Pattern Checklist
When dealing with Linked List data patterns.
Core Prerequisites
Revision Key Notes
Common Mistakes & Pitfalls
Related Questions
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Add and Update Keys in a Python Dictionary
Learn how to add elements or update key-value pairs in a Python dictionary. Explore square brackets, update method, and merge operator options.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.