Lessons
Arrays
- Two Sum Problem with Solution
- Best Time to Buy and Sell Stock
- Array Contains Duplicates
- Product of Array Except Self: Optimized Approach
- Maximum Subarray Problem
- Maximum Product Subarray
- Find Minimum in Rotated Sorted Array
- Search in Rotated Sorted Array
- Container With Most Water
- Verifying an Alien Dictionary
- Next Permutation
- Remove Duplicates from Sorted Array
- Find First and Last Position of Element in Sorted Array
- Trapping Rain Water
- Median of Two Sorted Arrays
Dynamic Programming
- Climbing Stairs Problem
- Coin Change Problem
- Longest Increasing Subsequence
- Longest Common Subsequence (LCS)
- Word Break Problem
- Combination Sum Problem
- House Robber Problem
- Decode Ways Problem
- Unique Paths Problem
- Pascal's Triangle Problem
- Generate Parentheses Problem
- Jump Game with Dynamic Programming and Greedy Algorithms
- Regular Expression Matching
- Race Car Problem
Graph
Add Two Numbers
Why the Add Two Numbers Problem Is More Than Just a Coding Question
The Add Two Numbers linked list problem is one of the most frequently asked coding interview questions. It's a problem that combines fundamental concepts such as linked list traversal, node creation, carry propagation, and memory-safe computation.
This problem is a favorite in technical interviews at companies like Google, Amazon, and Facebook. By mastering this problem, you’ll gain strong command over linked list operations and digit-wise algorithmic thinking.
This article explores how to solve the Add Two Numbers problem in the best possible way, using Python and focusing on edge cases, performance, and interview strategies.
What Is the Add Two Numbers Linked List Problem
You are given two non-empty linked lists that represent two non-negative integers. The digits are stored in reverse order, and each node contains a single digit. Your task is to add the two numbers and return the result as a linked list in the same reverse order format.
Example:
l1 = [2,4,3] represents the number 342
l2 = [5,6,4] represents the number 465
The sum is 807, which is returned as [7,0,8].
This problem is commonly known as add two numbers using linked list or linked list digit-wise addition with carry handling.
Why Reverse Order Digits Matter in Linked List Addition
In this problem, digits are stored in reverse order to simplify computation. This makes it easier to begin addition from the least significant digit, exactly how manual addition works.
Adding from the head of the list ensures that we can process both numbers simultaneously without the need to reverse them first or use recursion.
This structure also avoids additional memory overhead and leads to cleaner, more intuitive code.
Visual Explanation of Carry Handling in Add Two Numbers
Consider the two linked lists:
List 1: 2 → 4 → 3 (represents 342)
List 2: 5 → 6 → 4 (represents 465)
Step-by-step addition:
2 + 5 = 7, carry = 0 → new node: 7
4 + 6 = 10, carry = 1 → new node: 0
3 + 4 + 1 (carry) = 8, carry = 0 → new node: 8
Final linked list: 7 → 0 → 8, representing 807
This example demonstrates how carry propagation works node by node. Each sum is calculated with the current node values and the previous carry, producing the correct digit and the next carry value.
How to Solve Add Two Numbers – Step-by-Step Algorithm
This algorithm is both efficient and readable. It handles digits, carry, and varying list lengths gracefully.
- Create a dummy node to act as the head of the result list
- Initialize a pointer (current) to build the result
- Initialize carry to 0
- Loop through both input lists until all nodes are processed and carry is 0
- At each step:
- Add the values of the current nodes (or 0 if the list has ended)
- Add the carry
- Create a new node with the digit (total % 10)
- Update carry (total // 10)
- Move to the next nodes
This approach is iterative, efficient, and recommended for interviews.
Python Code: Add Two Numbers Using Linked List
Here is the clean and efficient Python implementation:
python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def addTwoNumbers(l1, l2): dummy = ListNode() current = dummy carry = 0 while l1 or l2 or carry: x = l1.val if l1 else 0 y = l2.val if l2 else 0 total = x + y + carry carry = total // 10 current.next = ListNode(total % 10) current = current.next if l1: l1 = l1.next if l2: l2 = l2.next return dummy.next
This solution covers:
- Add two numbers using carry
- Creation of a new linked list
- Handling of lists with unequal length
- Null safety with conditional access
What If the Two Lists Are of Different Lengths
A common question people ask is whether the algorithm works if the input lists are of different lengths.
Yes, it does. The loop condition while l1 or l2 or carry:
ensures that all nodes are processed, even when one list runs out before the other. Missing values are treated as 0.
Example:
List A: [9,9,9]
List B: [1]
Result: [0,0,0,1] (because 999 + 1 = 1000)
This scenario is handled without any special cases or additional loops.
Time and Space Complexity Analysis
Time complexity is linear with respect to the maximum length of the input lists. If m and n are the lengths of l1 and l2, then the time complexity is O(max(m, n)).
Space complexity is also O(max(m, n)) since we create a new node for each digit in the result.
The algorithm is efficient in both space and time, making it optimal for most use cases.
Common Mistakes and How to Avoid Them
Here are some common pitfalls and their fixes:
- Forgetting to check the carry after both lists are exhausted
- Incorrect pointer advancement after each iteration
- Using the same input nodes for the result, which leads to unexpected behavior
- Not handling null inputs safely
To avoid these, always use a dummy node to build the result list and advance pointers carefully.
Interview Readiness: What Interviewers Expect from You
During interviews, it’s not enough to just write code. You are expected to:
- Explain why you use a dummy node
- Describe how carry is handled across iterations
- Discuss edge cases like empty lists or large inputs
- Analyze time and space complexity
- Handle follow-up questions like reversing the list or forward-order representation
A strong understanding of linked list structure and control flow is critical. These problems all reinforce key skills like pointer manipulation, node creation, and edge-case handling.
Conclusion: Add Two Numbers with Linked Lists
The Add Two Numbers problem is a foundational linked list challenge that tests real-world coding skills. Understanding how to handle digits, carry, and list traversal will not only help you in interviews but also in system-level problem-solving.
From writing clear and bug-free code to explaining your choices to interviewers, solving this problem sharpens your algorithmic thinking. Whether you are targeting top tech jobs or improving your core data structure skills, mastering this problem is a step in the right direction.