TARGET DECK: Leetcode FILE TAGS: Medium


Intuition

  • The first time I tried this problem, I was unable to solve it since I overthought it by thinking you would have to reverse the linked list and stuff like that.
  • No, it is literally that you create nodes and save them one by one, being sure to pass a 1 if there is carryover.

Cards

START Basic Front: Add Two Numbers Back: Keep track of carryover similarly to Plus One

END

Code

Cleaned Up

# 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]:
        root = ListNode(-1)
        node = root
        carry_over = 0
        while l1 or l2 or carry_over:
            cur_sum = carry_over
            if l1:
                cur_sum += l1.val
                l1 = l1.next
            if l2:
                cur_sum += l2.val
                l2 = l2.next
 
            carry_over = cur_sum // 10
            node.next = ListNode(cur_sum % 10)
            node = node.next
 
        return root.next

Dirty

# 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]:
        root = ListNode(-1)
        node = root
        carry_over = 0
        while l1 or l2:
            cur_sum = 0
            if l1:
                cur_sum += l1.val
                l1 = l1.next
            if l2:
                cur_sum += l2.val
                l2 = l2.next
            cur_sum += carry_over 
 
            if cur_sum >= 10:
                carry_over = 1
                node.next = ListNode(cur_sum % 10)
            else:
                carry_over = 0
                node.next = ListNode(cur_sum)
            node = node.next
        
        if carry_over > 0:
            node.next = ListNode(carry_over)
 
        return root.next

Notes


References