AlgoMaster Logo

Add Two Numbers

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Iterative Approach

The naive approach involves iterating through both linked lists simultaneously, adding the digits, and managing the carry.

Intuition:

  • The core idea is to traverse both linked lists while simultaneously keeping track of the carry, resulting from the sum of respective digits.
  • When one of the linked lists is exhausted, continue the addition with the remaining linked list considering the carry.
  • If we are left with a carry after completely processing both lists, add a new node to represent that carry.

Algorithm:

  1. Initialize a dummyHead with value 0. This will help to easily return the head of the new linked list.
  2. Initialize current pointer to point at dummyHead.
  3. Initialize a variable carry to 0.
  4. Loop over the linked lists as long as there are digits to process from either one or there is a carry to consider.
    • Compute the sum of the current digits (considering null to represent value 0) and the carry.
    • Update the carry based on the sum (it'll be either 0 or 1).
    • Create a new node with the digit value of sum % 10 and attach it to current.
    • Advance to the next nodes in the linked lists as well as move current.
  5. Return dummyHead.next.

Code: