Add Two Number — Day 15(Python)

Photo by boris misevic on Unsplash

Today we will be looking at one of the frequently asked questions in a technical coding interview.

2. Add Two Numbers

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:

Example 2:

Example 3:

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

  1. Initialize carry as 0 since we do not have a carry-forward number when we start our addition.
  2. While we have elements in both the linked-list add both numbers along with the carry-forward number.
  3. Consider the resulting answer unit digit as a node in the linked list and other digits as the carry-forward number.
  4. Repeat step 2 and 3 until one of the linked lists reach the end.
  5. If any of the linked-list is yet to be visited, add the remaining nodes with the carry-forward number.

Time Complexity

We are traversing through both the list at the same time and hence the time complexity is O(max(M, N)) where M, N is the length of both the LinkedList.

Space Complexity

We are creating a new LinkedList as an output that would take O(max(M, N)) where M, N is the length of both the LinkedList.

I would love to hear your feedback about my posts. Do let me know if you have any comments or feedback.

Software Engineer. Find me @ www.linkedin.com/in/annamariya-jt