↓Skip to main content
  1. LeetCode/

LeetCode 2: Add Two Numbers

·2 mins· ·
LeetCode Medium Linked-List Math Recursion
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-02-19

  • Submissions: Runtime Error ×14 → Wrong Answer → Accepted → Runtime Error ×3 → Wrong Answer ×3 → Accepted ×2

Approach
#

The ones digit is at the head, so addition starts from the head (Linked List Template 1). A dummy collects the result; each digit is (a + b + carry) % 10 and the new carry is // 10. Looping on l1 or l2 or carry handles both unequal lengths and a final carry at once.

My Attempts
#

This was from my first LeetCode attempts in February 2022, 24 submissions:

  • The first dozen REs came from not knowing ListNode: calling ''.join on a list node, converting to strings and reversing, or reading .val on None.
  • Once I could use the list, one version moved the dummy itself as the tail, so return res.next was no longer the head and returned nothing.
  • One version dropped the final carry: [6] + [7] should be [3, 1]; it returned [3].

Solution
#

class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        tail = dummy = ListNode()
        carry = 0
        while l1 or l2 or carry:
            s = carry + (l1.val if l1 else 0) + (l2.val if l2 else 0)
            carry, digit = divmod(s, 10)
            tail.next = tail = ListNode(digit)
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None
        return dummy.next

Complexity
#

Time O(max(m, n)), space O(1) besides the output.

Mistakes to Avoid
#

  • A final carry becomes a node too.
  • Keep the tail pointer separate from the dummy, or the head is lost.

Interview Explanation
#

With reversed digits I add from the head with a carry, building the result after a dummy. The loop runs until both lists end and no carry remains, so unequal lengths and a final carry need no extra code. Time O(max(m, n)).

Related

LeetCode 7: Reverse Integer
·2 mins
LeetCode Medium Math
LeetCode 7 note: remember the sign, reverse the digits of the absolute value, and return 0 when the result leaves the signed 32-bit range
LeetCode 9: Palindrome Number
·2 mins
LeetCode Easy Math
LeetCode 9 note: negatives are never palindromes; without strings, reverse the second half of the digits and compare it with the first half
LeetCode 13: Roman to Integer
·1 min
LeetCode Easy Hash-Table Math String
LeetCode 13 note: add each symbol’s value left to right, subtracting instead when it is smaller than the symbol to its right
LeetCode 197: Rising Temperature
·1 min
LeetCode Easy Database
LeetCode 197 note: self-join Weather on a one-day date difference with today warmer; compare dates with DATEDIFF, never ids
LeetCode 595: Big Countries
·1 min
LeetCode Easy Database
LeetCode 595 note: filter with WHERE and OR for an area of at least 3 million or a population of at least 25 million
LeetCode 596: Classes With at Least 5 Students
·1 min
LeetCode Easy Database
LeetCode 596 note: group by class with HAVING COUNT(DISTINCT student) >= 5; older test data had duplicate rows, so count distinct students