2. Add Two Numbers

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 contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

Time Complexity

  • Time complexity: O(max(m, n))

  • Space complexity: O(max(m, n)) – at most max(m, n) + 1

Code

class Solution:
    def addTwoNumbers(self, l1, l2):
        if l1 == None or l2 == None:
            return l2 if l1 == None else l1
        
        head = l1
        pre, c = None, 0
        
        while l1 and l2:
            s = l1.val + l2.val + c #sum
            l1.val = s % 10
            c = x // 10
            l1 = l1.next 
            l2 = l2.next 
            pre = head if pre == None else pre.next
            
        if l1 == None: 
            pre.next = l2
            
        left = pre.next 
        
        while left != None: 
            x = left.val + c
            left.val = x % 10 
            c = x // 10
            left = left.next
            pre = pre.next #keep tracking in case left == null
        
        if c == 1: 
            pre.next = ListNode(1)
            
        return head

Last updated