Table of Content
Problem statement
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
Solution
Time Complexity: O(N)
Space Complexity: O(1)
The objective here is to take 2 numbers arranged as linked list and construct a final linked list representing the sum. The key to solve this problem is to understand carry
, in which we transfer a digit from one digit to another. There are also 2 edge cases that we need to cover:
- When the two linked list are not the same size.
- When the sum of the last 2 digits produces a
carry
To solve this problem, we will need to
- Create a variable to help us keep track of the
carry
. - Initialize a
output
linked list, along with a variable as our reference iterator, so we don’t lose reference to thehead
of the linked list. - Iterate through both of the linked list. If one is shorter than the other, we’ll continue iterating through the larger one.
- At the end of the
loop
, make sure to account for the edge case, where the sum of the last 2 digits produces acarry
, which we handle by constructing a newListNode
with the value,1
. For example, two linked list,[5,5]
,[5,5]
, will output[0,1,1]
. The last1
in[0,1,1]
is the result of the edge case.
Complexity Explanation
Since we’re iterating through both linked list at the same time using only one while
loop as well as constructing our final output
, the time complexity is only O(N)
, where N
is the size of the larger linked list.
Because we’ve only created two variables, one to hold number, and one as reference, the space complexity is only O(1)
as they both taken up constant space.