Leetcode 2: Add Two Numbers

grid47
grid47
Exploring patterns and algorithms
Nov 6, 2024 6 min read

Two radiant number paths merging into one continuous light beam, symbolizing addition.
Solution to LeetCode 2: Add Two Numbers Problem

You are given two linked lists representing two non-negative integers, where each node contains a single digit, and the digits are stored in reverse order. Your task is to add these two numbers and return the result as a linked list. You can assume that the input does not contain leading zeros except for the number 0 itself.
Problem
Approach
Steps
Complexity
Input: The input consists of two linked lists representing integers in reverse order.
Example: l1 = [1, 2, 3], l2 = [4, 5, 6]
Constraints:
• 1 <= number of nodes in each linked list <= 100
• 0 <= Node.val <= 9
• The lists represent valid non-negative integers without leading zeros, except for 0 itself.
Output: The output is a linked list representing the sum of the two input integers in reverse order.
Example: [5, 7, 9]
Constraints:
• The resulting linked list must maintain reverse order.
• Each node in the linked list must have a value between 0 and 9.
Goal: To compute the sum of two integers represented as linked lists in reverse order and return the result as a linked list.
Steps:
• Initialize a dummy node to start the result linked list.
• Iterate through the two input linked lists while maintaining a carry for digit sums exceeding 9.
• Add corresponding digits from both lists along with the carry to calculate the sum.
• Create a new node for the result of each addition and append it to the result linked list.
• Continue until both lists are traversed and there is no carry left.
• Return the result linked list starting from the node next to the dummy.
Goal: Conditions that the input will always meet.
Steps:
• The input lists represent integers stored in reverse order.
• The result does not have leading zeros unless the number is 0.
Assumptions:
• The input is always valid.
• Both linked lists represent non-negative integers.
Input: l1 = [3, 4, 2], l2 = [4, 6, 5]
Explanation: The numbers represented are 243 and 564. Their sum is 807, so the output is [7, 0, 8].

Input: l1 = [0], l2 = [0]
Explanation: The numbers represented are 0 and 0. Their sum is 0, so the output is [0].

Input: l1 = [9, 9, 9], l2 = [1]
Explanation: The numbers represented are 999 and 1. Their sum is 1000, so the output is [0, 0, 0, 1].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus