Taro Logo

Add Two Numbers

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+22
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
2.4K views
Topics:
Linked Lists

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:

  • The number of nodes in each linked list is in the range [1, 100].
  • 0 <= Node.val <= 9
  • It is guaranteed that the list represents a number that does not have leading zeros.

Solution


Clarifying Questions

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:

  1. Could the two linked lists be of significantly different lengths, and how should we handle the missing digits?
  2. Is the output linked list also expected to store the digits in reverse order, just like the input lists?
  3. What should we return if one or both of the input linked lists are empty or null?
  4. Can each node contain values greater than 9, or is it strictly guaranteed that each node holds a single decimal digit from 0 to 9?
  5. Should we modify the existing linked lists in place to construct the result, or allocate a completely new linked list for the sum?

Brute Force Solution

Approach

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:

  1. Start by looking at the first piece of paper and write down the full number it represents by reading the digits in reverse order.
  2. Next, look at the second piece of paper and do the exact same thing to find its full numerical value.
  3. Take these two full numbers and add them together just like you would on standard scratch paper.
  4. Take the resulting sum and break it apart, digit by digit, from right to left.
  5. Create a brand new sequence of items representing these individual digits in the exact same reverse order as the original pieces of paper.
  6. Hand over this new sequence as your final answer.

Code Implementation

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.next

Big(O) Analysis

Time Complexity
O(n + m) – The brute force strategy first traverses the first linked list of length n to reconstruct its full numerical value, taking O(n) steps. Next, it traverses the second linked list of length m to reconstruct the second value, taking O(m) steps, followed by standard arithmetic which scales with the number of digits. Finally, it breaks down the resulting sum into individual digits to build a new linked list, which takes proportional time to the number of digits in the sum. Combining these sequential passes results in approximately n + m + max(n, m) operations, which simplifies to a linear time complexity of O(n + m).
Space Complexity
O(max(N, M)) – The plain English approach requires reading the input lists to form full numbers, storing intermediate sums, and building a brand new sequence of digits to return as the final answer. The extra memory is driven by this newly created output linked list, whose length is proportional to the length of the longer input list. If we define N as the maximum length between the two input lists, the auxiliary space used to construct the result grows linearly with N. Therefore, the total extra memory simplifies to Big O of N.

Optimal Solution

Approach

The 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:

  1. Line up both numbers so their starting digits are aligned, just like you would on a sheet of paper.
  2. Keep track of any overflow value, starting with none since nothing has been added yet.
  3. Look at the current pair of digits from both numbers, along with any overflow carried over from the previous step.
  4. Add these values together to get a combined total for the current position.
  5. If the combined total is ten or greater, keep only the final digit for the current position and save the extra amount as a new overflow for the next step.
  6. Write down the kept digit as part of your final answer.
  7. Move forward to the next pair of digits and repeat the process until every digit has been accounted for.
  8. If you reach the end of both numbers but still have a leftover overflow value, create one final position to include it in your answer.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(max(n, m)) – The cost is driven by traversing both linked lists node by node until we reach the end of the longer list, where n and m represent the lengths of the two input lists. In each step of the traversal, we perform a constant amount of work consisting of adding the digits, calculating the carry, and creating a new result node. Therefore, the total number of operations grows linearly with the length of the longer number, which approximates to max(n, m) operations and simplifies to O(max(n, m)).
Space Complexity
O(max(N, M)) – The auxiliary space is driven by the newly created linked list that stores the result of the addition. The number of nodes in this output list is proportional to the length of the longer input list, plus at most one additional node if there is a final overflow carry. Therefore, auxiliary memory scales linearly with the size of the larger input, denoted as N.

Edge Cases

Linked lists of unequal length
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
The carry variable propagates naturally through subsequent nodes in each iteration until it is finally absorbed or appended.
0/75 completed