You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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 = [7,2,4,3], l2 = [5,6,4] Output: [7,8,0,7]
Example 2:
Input: l1 = [2,4,3], l2 = [5,6,4] Output: [8,0,7]
Example 3:
Input: l1 = [0], l2 = [0] Output: [0]
Constraints:
[1, 100].0 <= Node.val <= 9Follow up: Could you solve it without reversing the input lists?
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:
Imagine you have two numbers represented as lists, with each digit being a list item. The brute force approach involves converting each list into actual whole numbers, adding them together, and then converting the result back into a list of digits.
Here's how the algorithm would work step-by-step:
def add_two_numbers_ii_brute_force(list1, list2):
first_number = 0
for digit in list1:
first_number = first_number * 10 + digit
second_number = 0
for digit in list2:
second_number = second_number * 10 + digit
# Convert the lists to numbers and find their sum.
total_sum = first_number + second_number
result_list = []
# Handle the case where the sum is zero.
if total_sum == 0:
return [0]
# Convert the sum back into a list of digits.
while total_sum > 0:
digit = total_sum % 10
# Extract digits and add to result.
result_list.insert(0, digit)
total_sum //= 10
return result_listThe challenge is to add two numbers that are represented as linked lists, where the most significant digit comes first. The clever trick is to use stacks to reverse the order of digits without actually modifying the lists, allowing us to add from the least significant digit, just like we do with pen and paper.
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):
stack1 = []
stack2 = []
while list1:
stack1.append(list1.val)
list1 = list1.next
while list2:
stack2.append(list2.val)
list2 = list2.next
carry = 0
result = None
# Process digits from stacks, simulating adding from right to left
while stack1 or stack2 or carry:
digit1 = stack1.pop() if stack1 else 0
digit2 = stack2.pop() if stack2 else 0
sum_of_digits = digit1 + digit2 + carry
carry = sum_of_digits // 10
digit = sum_of_digits % 10
# Construct new node at the beginning of result list
new_node = ListNode(digit)
new_node.next = result
result = new_node
return result| Case | How to Handle |
|---|---|
| Both input lists are null or empty. | Return null (or an empty list) if both input lists are null, indicating a sum of zero. |
| One list is null or empty while the other is not. | Treat the null/empty list as representing zero, and effectively just return the non-null list. |
| Input lists have significantly different lengths. | Pad the shorter list with leading zeros (conceptually, using stacks to align) to ensure correct digit-by-digit addition. |
| Sum results in a carry-over to a new most significant digit. | Add a new node with the carry-over value at the head of the resulting list. |
| Input lists represent very large numbers that might cause integer overflow if converted to native integer types. | The linked list representation itself handles arbitrarily large numbers, as intermediate calculations are done digit by digit, so no overflow should occur. |
| All digits in one or both lists are zeros. | Handle the case correctly, resulting in a single node with the value zero, unless both lists are empty. |
| Carry propagation through many digits. | Ensure the carry is propagated correctly through multiple nodes during the digit-by-digit addition, updating each node's value and carry appropriately. |
| Leading zeros are present in either of the input lists (other than single 0) | While the problem states the lists represent non-negative integers, handle leading zeros by stripping them, or include logic during addition not to include the leading zeros. |