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.
Example 1:
Input: l1 = [2,4,3], l2 = [5,6,4] Output: [7,0,8] Explanation: 342 + 465 = 807.
Example 2:
Input: l1 = [0], l2 = [0] Output: [0]
Example 3:
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] Output: [8,9,9,9,0,0,0,1]
Constraints:
[1, 100]
.0 <= Node.val <= 9
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The most direct way to solve this is to treat it like a simple arithmetic problem. We'll first convert each list of digits into the actual number it represents, then add these two numbers together using standard math, and finally, convert the sum back into a new list of digits.
Here's how the algorithm would work step-by-step:
class ListNode:
def __init__(self, value=0, next_node=None):
self.value = value
self.next_node = next_node
def add_two_numbers_brute_force(first_list, second_list):
first_number = 0
second_number = 0
multiplier = 1
current_node = first_list
while current_node is not None:
# Build the complete number by adding the value of each digit scaled by its position.
first_number = first_number + current_node.value * multiplier
multiplier = multiplier * 10
current_node = current_node.next_node
multiplier = 1
current_node = second_list
while current_node is not None:
# Replicate the number conversion process for the second list.
second_number = second_number + current_node.value * multiplier
multiplier = multiplier * 10
current_node = current_node.next_node
sum_of_numbers = first_number + second_number
dummy_head = ListNode()
current_new_node = dummy_head
if sum_of_numbers == 0:
return ListNode(0)
# Convert the calculated sum back into a list of digits in reverse order.
while sum_of_numbers > 0:
digit = sum_of_numbers % 10
current_new_node.next_node = ListNode(digit)
current_new_node = current_new_node.next_node
sum_of_numbers = sum_of_numbers // 10
# The dummy head was used to simplify list creation, so we return the actual starting node.
return dummy_head.next_node
The best way to solve this is to mimic how you'd add two large numbers by hand, column by column, from right to left. We'll start with the first digit of each number, add them up, and keep track of any amount we need to carry over to the next column, just like grade-school math.
Here's how the algorithm would work step-by-step:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def addTwoNumbers(list_one, list_two):
dummy_head = ListNode(0)
current_result_node = dummy_head
carry_over = 0
pointer_one = list_one
pointer_two = list_two
# Iterate through both lists until all digits are processed.
while pointer_one is not None or pointer_two is not None:
value_one = pointer_one.val if pointer_one is not None else 0
value_two = pointer_two.val if pointer_two is not None else 0
current_sum = value_one + value_two + carry_over
# The new carry is the tens digit of the sum (e.g., 1 from 15).
carry_over = current_sum // 10
new_digit = current_sum % 10
current_result_node.next = ListNode(new_digit)
current_result_node = current_result_node.next
if pointer_one is not None:
pointer_one = pointer_one.next
if pointer_two is not None:
pointer_two = pointer_two.next
# If there's a leftover carry after the last addition, it must be the most significant digit.
if carry_over > 0:
current_result_node.next = ListNode(carry_over)
# The dummy head's next node is the actual start of our resulting list.
return dummy_head.next
Case | How to Handle |
---|---|
Input lists of different lengths | The algorithm should treat missing nodes on the shorter list as having a value of zero. |
Sum results in a carry on the most significant digit | A new node must be created for the final carry value after the main loop finishes. |
One or both input lists are null | The problem states inputs are non-empty, but robust code should return the non-null list or null if both are null. |
One or both input lists contain a single node | The general iterative approach handles this case correctly without any special logic. |
Input numbers are very large, leading to long lists | A standard iterative solution handles this efficiently with O(max(N, M)) time and space complexity. |
Input lists representing the number zero (a single node with value 0) | Adding a list representing zero to another list should correctly return a copy of the other list. |
The sum of digits at a position is exactly 9 with a carry-in of 1 | This correctly results in a node with value 0 and a carry-out of 1, which the loop logic must handle. |
Potential for integer overflow if converting lists to numbers | The digit-by-digit summation approach avoids this language-specific overflow issue entirely. |