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:

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:

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.
class LinklistAdder:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
new_node = ListNode(0)
main_node = new_node
carry = 0
while(l1 and l2):
addition = l1.val + l2.val + carry
new_node.next = ListNode(addition%10)
carry = addition//10
new_node = new_node.next
l1 = l1.next
l2 = l2.next
while l1:
addition = l1.val+carry
new_node.next = ListNode(addition%10)
carry = addition//10
new_node = new_node.next
l1 = l1.next
while l2:
addition = l2.val+carry
new_node.next = ListNode(addition%10)
carry = addition//10
new_node = new_node.next
l2 = l2.next
if carry:
new_node.next = ListNode(carry)
return main_node.next

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store