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.
Example 1:
Input: l1 = [2,4,3], l2 = [5,6,4] Output: [7,0,8] Explanation: 342 + 465 = 807.
Intuition
The problem involves adding two numbers represented by linked lists. Since the digits are stored in reverse order, we can traverse both linked lists simultaneously, add the corresponding digits along with any carry from the previous step, and construct the resulting linked list.
Approach
Initialize variables carry and dummy to 0 and a dummy node, respectively. Also, initialize current to the dummy node.
Traverse both linked lists simultaneously until reaching the end of both lists.
At each step, compute the sum of the corresponding digits along with the carry from the previous step.
Update the carry for the next step and create a new node with the current digit of the sum.
Move to the next nodes in both linked lists and the resulting linked list.
After the traversal, check if there is any remaining carry. If so, create a new node with the carry.
Return the head of the resulting linked list (dummy.next).
Complexity
- Time complexity:
The time complexity is O(max(m, n)), where m and n are the lengths of the two linked lists. The algorithm traverses both linked lists once.
- Space complexity:
The space complexity is O(max(m, n)) since the solution uses additional space to store the resulting linked list.
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
count = 0
sum1 = sum2 = 0
first , second = l1 , l2
while first:
val1 = first.val
sum1 += val1 * (10 ** count)
first = first.next
count += 1
temp = count
count = 0
while second:
val2 = second.val
sum2 += val2 * (10 ** count)
second = second.next
count += 1
if (sum1 + sum2) // count == 0:
total = (sum1 + sum2) % (10 ** max(temp , count))
else:
total = (sum1 + sum2) % (10 ** (max(temp , count) + 1))
dummy = ListNode()
current = dummy
for digit in str(total)[::-1]:
current.next = ListNode(int(digit))
current = current.next
return dummy.next