Add Two Numbers

The "Add Two Numbers" problem is another fundamental challenge in the realm of algorithms and data structures, primarily focusing on linked lists. Let's dissect this problem from its basic principles.

Problem Statement:

  1. Input: 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.
  2. Goal: Add the two numbers and return the sum as a linked list.

Key Concepts:

  • Linked List: A linear collection of data elements, where each element (node) points to the next. It allows for efficient insertions or deletions of elements from any position in the sequence.
  • Digit-by-Digit Addition: The way we usually add numbers (starting from the least significant digit and moving to the most significant, carrying over as needed).

Solution Approach:

Basic Steps:

  1. Traverse both linked lists simultaneously, starting from the head nodes.
  2. Add corresponding digits, including any carry from the previous digit's addition.
  3. Store the result's last digit in a new node of the resulting linked list.
  4. If the sum of two digits is 10 or more, carry over the higher digit to the next addition.
  5. Continue until both linked lists are completely traversed.
  6. If there is an extra carry after the final iteration, create an additional node with this carry.

Time and Space Complexity:

  • Time Complexity: O(max(m, n)), where m and n are the lengths of the two linked lists. We process each element at most once.
  • Space Complexity: O(max(m, n)), as a new linked list is created to hold the results, which in the worst case will be as long as the longer of the two input lists, plus possibly one additional node for an extra carry.

Example Implementation in Python:

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def add_two_numbers(l1, l2):
    """
    Adds two numbers represented by linked lists.

    Args:
    l1 (ListNode): The first linked list.
    l2 (ListNode): The second linked list.

    Returns:
    ListNode: The head of the linked list representing the sum.
    """
    # Initialize the dummy head of the result list.
    dummy_head = ListNode(0)
    current = dummy_head
    carry = 0

    # Loop through lists l1 and l2 until you reach both ends.
    while l1 is not None or l2 is not None:
        # At the start of each iteration, should add the carry from last iteration.
        sum = carry
        if l1 is not None:
            sum += l1.val
            l1 = l1.next
        if l2 is not None:
            sum += l2.val
            l2 = l2.next

        # Update carry for next iteration
        carry = sum // 10

        # Create a new node with the digit value of (sum mod 10) and set it as the current node's next, then move to this new node.
        current.next = ListNode(sum % 10)
        current = current.next

    # Check if there is a carry left after the final iteration.
    if carry > 0:
        current.next = ListNode(carry)

    # Return the dummy head's next node.
    return dummy_head.next

This code snippet demonstrates a fundamental approach to solving the "Add Two Numbers" problem, focusing on:

  • Basic operations in a linked list, such as traversal and node creation.
  • Simple arithmetic operations, with a focus on handling the carry in addition.
  • Ensuring that the solution is robust to handle lists of different lengths and the presence of an additional carry after the final addition.

PrevNext