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:
We're given two numbers represented as linked lists, and need to add them together. A brute force approach involves converting each linked list into regular numbers, adding the numbers, and then converting the result back into a linked list.
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 add_two_numbers_brute_force(list_one, list_two):
def linked_list_to_integer(linked_list):
number = 0
power_of_ten = 1
current_node = linked_list
while current_node:
number += current_node.val * power_of_ten
power_of_ten *= 10
current_node = current_node.next
return number
# Convert the linked lists to integers
number_one = linked_list_to_integer(list_one)
number_two = linked_list_to_integer(list_two)
# Add the numbers together
total_sum = number_one + number_two
# Handle the case where the sum is zero
if total_sum == 0:
return ListNode(0)
# Convert the sum to a linked list
head = None
tail = None
while total_sum > 0:
digit = total_sum % 10
total_sum //= 10
new_node = ListNode(digit)
# Build linked list, setting head
if not head:
head = new_node
tail = new_node
else:
tail.next = new_node
tail = new_node
return head
The key is to simulate adding the numbers the same way you would do it on paper, digit by digit, handling any carry-over values as you go. We process both numbers simultaneously, starting from their least significant digits, and build the result one digit at a time.
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(list1, list2):
carry = 0
dummy_head = ListNode(0)
current_node = dummy_head
while list1 or list2:
value_list1 = list1.val if list1 else 0
value_list2 = list2.val if list2 else 0
# Sum the digits and account for any carry
digit_sum = value_list1 + value_list2 + carry
# Determine the new carry for the next iteration
carry = digit_sum // 10
current_node.next = ListNode(digit_sum % 10)
current_node = current_node.next
if list1:
list1 = list1.next
if list2:
list2 = list2.next
# Add the final carry if it exists
if carry > 0:
current_node.next = ListNode(carry)
return dummy_head.next
Case | How to Handle |
---|---|
Both input lists are empty (null) | Return a linked list with a single node containing 0 or return null, depending on the specific requirement; handle by checking for null lists at the beginning and returning a appropriate value. |
One list is empty (null), the other is not | Treat the empty list as a list of zeros, allowing the non-empty list to be returned or used in calculation with the zero list. |
Lists of significantly different lengths | Iterate until both lists are exhausted, handling remaining digits of the longer list with a possible carry-over. |
Large numbers causing integer overflow | Use `long` data type to store intermediate sums to avoid immediate overflow, then mod by 10 before assigning to Node. |
Carry-over at the most significant digit | After processing all digits, check for a remaining carry and add a new node to the end of the result list if needed. |
One or both input lists contain a single node with value 0 | The algorithm should correctly handle lists with a single node having a value of zero and properly add it with the other number, accounting for potential carry-over. |
Resultant sum is zero | Return a linked list containing a single node with value 0. |
Very long lists that could exhaust memory | The solution uses constant extra space for the carry value and the result list nodes, so scalability is determined by the size of the input, but creation of a very long list could lead to memory issues. |