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 <= 9When 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:
Imagine you have two very long numbers written backwards on pieces of paper, digit by digit. The brute force approach involves reading the numbers in their entirety, converting them into standard whole numbers, adding them together normally, and then breaking the final sum back down into individual digits to create a new 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 addTwoNumbers(l1: ListNode, l2: ListNode) -> ListNode:
# Traverse the first linked list to reconstruct its full numerical value
multiplier_one = 1
number_one = 0
current_node_one = l1
while current_node_one is not None:
number_one += current_node_one.val * multiplier_one
multiplier_one *= 10
current_node_one = current_node_one.next
# Traverse the second linked list to reconstruct its full numerical value
multiplier_two = 1
number_two = 0
current_node_two = l2
while current_node_two is not None:
number_two += current_node_two.val * multiplier_two
multiplier_two *= 10
current_node_two = current_node_two.next
# Calculate the standard mathematical sum of both fully reconstructed numbers
total_sum = number_one + number_two
# Handle edge case where the total sum is zero by returning a single node
if total_sum == 0:
return ListNode(0)
dummy_head = ListNode(0)
tail_pointer = dummy_head
# Break down the total sum digit by digit to build the resulting linked list
while total_sum > 0:
remainder_digit = total_sum % 10
tail_pointer.next = ListNode(remainder_digit)
tail_pointer = tail_pointer.next
total_sum //= 10
return dummy_head.nextThe optimal approach mimics how you add numbers on paper by lining up the digits and moving from right to left. It processes each pair of corresponding digits together and handles any overflow by carrying it over to the next column.
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(l1: ListNode, l2: ListNode) -> ListNode:
dummy_head = ListNode(0)
current_node = dummy_head
carry_value = 0
# Traverse both lists simultaneously to process corresponding digit positions.
while l1 is not None or l2 is not None:
digit_sum = carry_value
if l1 is not None:
digit_sum += l1.val
l1 = l1.next
if l2 is not None:
digit_sum += l2.val
l2 = l2.next
# Compute carry for the next position if the sum exceeds single digit limits.
carry_value = digit_sum // 10
current_node.next = ListNode(digit_sum % 10)
current_node = current_node.next
# Append a final node if any overflow remains after the lists are exhausted.
if carry_value > 0:
current_node.next = ListNode(carry_value)
return dummy_head.next| Case | How to Handle |
|---|---|
| Linked lists of unequal length | The traversal loop continues through both lists independently, treating any exhausted list as having a value of zero. |
| A final carry-over after both lists are fully traversed | A final check is performed after the main loop to append a new node with a value of one if a carry remains. |
| Single-digit inputs that sum to less than ten | The algorithm simply creates a single new node containing the sum and completes without creating any carry. |
| Inputs representing zero as a single node with value zero | The pointers process the zero nodes normally, summing them to zero and returning a single node with value zero. |
| Extremely long linked lists representing very large numbers | The iterative single-pass approach processes nodes sequentially in linear time and constant extra space without risking integer overflow. |
| Cascading carries spanning multiple sequential nines | The carry variable propagates naturally through subsequent nodes in each iteration until it is finally absorbed or appended. |