Coding Challenge from Leetcode - Add Two Numbers!

KG.codes · 1 minute read ·     

Here is the problem and solution to a coding challenge from Leetcode.com called Add Two Numbers!

Problem

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.

Add two numbers from Leetcode

Intuition / Tip

Iterate through both linked lists simultaneously, adding corresponding digits. Handle carry-over whenever the sum exceeds 9, and make sure to process any remaining carry after reaching the end of both lists.

Solution Steps

  1. Initialize pointers for both linked lists and a dummy node for the result.
  2. Set up a carry variable to store sums greater than 9.
  3. Iterate through the lists, adding corresponding digits along with the carry.
  4. Create new nodes in the result list to store the sum of the digits.
  5. Handle cases where one list is longer than the other.
  6. Add a final node if there is a remaining carry after both lists are processed.

Time Complexity

O(max(n, m)), where n and m are the lengths of the two linked lists, as we iterate through both lists.

Add two numbers time complexity

Space Complexity

O(max(n, m)), since we create a new linked list to store the result, with space proportional to the larger of the two inputs.

Add two numbers space complexity

External Resources

Let me know if you have any questions or see ways I could have optimized!

Want to share this?