Add Two Numbers II Problem
Description
LeetCode Problem 445.
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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:
Input: l1 = [7,2,4,3], l2 = [5,6,4]
Output: [7,8,0,7]
Example 2:
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [8,0,7]
Example 3:
Input: l1 = [0], l2 = [0]
Output: [0]
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.
Solution
Approach: Two Stacks
Addition starts at the least significant digit, but here the lists start at the most significant one, and a singly linked list cannot be walked backwards. Converting to built-in integers fails too, since a list can hold 100 digits.
A stack reverses the order for us:
- Push every digit of
l1onto one stack and every digit ofl2onto another. Popping now yields the digits from last to first. - While either stack has digits or there is a carry, pop one digit from each non-empty stack, add them with the carry, and split the total into
total % 10(this digit) andtotal / 10(the new carry). - The digits come out from least to most significant, so prepend each new node:
head = ListNode(digit, head). When the loop ends,headpoints at the most significant digit, and nothing has to be reversed.
Two details: the lists may have different lengths, so a stack that runs out just contributes 0; and the loop must keep going while carry > 0, otherwise [9,9,9] + [1] would lose its leading 1 and give [0,0,0] instead of [1,0,0,0].
This leaves the input lists unchanged, which reversing them in place would not.
Complexity: O(m + n) time and O(m + n) space for the stacks, where m and n are the lengths of the two lists.
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
# Push the digits so that popping gives them from the least significant one.
digits1, digits2 = [], []
while l1:
digits1.append(l1.val)
l1 = l1.next
while l2:
digits2.append(l2.val)
l2 = l2.next
head = None # the sum is built from its last digit to its first
carry = 0
while digits1 or digits2 or carry:
total = carry
if digits1:
total += digits1.pop()
if digits2:
total += digits2.pop()
head = ListNode(total % 10, head) # prepend the new digit
carry = total // 10
return head