Skip to content

Latest commit

 

History

History
137 lines (113 loc) · 4.99 KB

2.Add_Two_Numbers_(Medium).md

File metadata and controls

137 lines (113 loc) · 4.99 KB

2. Add Two Numbers (Medium)

Link: https://leetcode.com/problems/add-two-numbers/

Date and Time: May 26, 2024
Update: Jul 30, 2024


Question:

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:

drawing

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:

  • 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.


Walk-through:

The second solution counts the sum of l1, l2 under the conditions that while l1 and l2. After that, if either l1 or l2 has extra nodes, we checking the rest and append them into tail.next.

First, create a dummy head for the new linkedlist so that we can append the new sum.
Then each time in the while loop, set x, y to be l1.val, l2.val or 0 when one list is shorter than the another one.
Next, we update the carry based on the sum and append the new node of the sum % 10. Lastly, check the edge case if the last sum leads to an additional slot in the new linkedlist, if so, we just add it to the next with carry.

drawing


Python Solution (Optimized):

# 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]:
        carry = 0
        dummy = tail = ListNode()
        while l1 or l2:
            x = l1.val if l1 else 0
            y = l2.val if l2 else 0
            curr = x + y + carry
            carry = curr // 10
            tail.next = ListNode(curr % 10)
            tail = tail.next
            if l1: l1 = l1.next
            if l2: l2 = l2.next
        if carry:
            tail.next = ListNode(carry)
        return dummy.next

Time Complexity: $O(\text{len(l1)} + \text{len(l2)})$
Space Complexity: $O(\text{len(l1)} + \text{len(l2)})$

Intuitive Solution:

# 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]:
        carry = 0
        dummy = tail = ListNode()
        while l1 and l2:
            curr = l1.val + l2.val + carry
            remainder = curr % 10
            if curr > 9:
                carry = 1
            else:
                carry = 0
            tail.next = ListNode(remainder)
            l1, l2 = l1.next, l2.next
            tail = tail.next
        if l1:
            while l1:
                curr = l1.val + carry
                remainder = curr % 10
                if curr > 9:
                    carry = 1
                else:
                    carry = 0
                tail.next = ListNode(remainder)
                l1 = l1.next
                tail = tail.next
        elif l2:
            while l2:
                curr = l2.val + carry
                remainder = curr % 10
                if curr > 9:
                    carry = 1
                else:
                    carry = 0
                tail.next = ListNode(remainder)
                l2 = l2.next
                tail = tail.next
        if carry:
            tail.next = ListNode(carry)
        return dummy.next

CC BY-NC-SABY: credit must be given to the creatorNC: Only noncommercial uses of the work are permittedSA: Adaptations must be shared under the same terms