LeetSolved

Find solutions to all LeetCode problems here.

2.

Add Two Numbers

Medium

Problem Description

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.

Examples

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.

Input: l1 = [0], l2 = [0]
Output: [0]

Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]

Constraints

Approach to Solve

Traverse both lists simultaneously, adding corresponding digits and keeping track of the carry. Create a new linked list to store the result.

Code Implementation

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        dummy = ListNode(0)
        current = dummy
        carry = 0
        while l1 or l2 or carry:
            val1 = l1.val if l1 else 0
            val2 = l2.val if l2 else 0
            total = val1 + val2 + carry
            carry = total // 10
            current.next = ListNode(total % 10)
            current = current.next
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None
        return dummy.next

Explanation

We iterate through both linked lists simultaneously, adding the corresponding digits and any carry from the previous addition. We create a new linked list to store the result. The time and space complexity are both O(max(n, m)), where n and m are the lengths of the input linked lists.

Complexity

  • Time Complexity: O(max(n, m))
  • Space Complexity: O(max(n, m))
Code copied to clipboard!