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 zeros, except the number 0
itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
Keep track of the carry using a variable and simulate digits-by-digits sum starting from the head of list, which contains the least-significant digit.
</img>
Figure 1. Visualization of the addition of two numbers: 342 + 465 = 807. Each node contains a single digit and the digits are stored in reverse order.
Just like how you would sum two numbers on a piece of paper, we begin by summing the least-significant digits, which is the head of LL1 and LL2.
Since each digit is in the range of 0...9
, summing two digits may “overflow”. For example 5 + 7 = 12. In this case, we set the current digit to 2
and bring over the carry = 1
to the next iteration. carry
must be either 0
or 1
because the largest possible sum of two digits (including the carry) is 9 + 9 + 1 = 19
.
The pseudocode is as following:
carry
to 0
.p
and q
to head of LL1
and LL2
respectively.LL1
and LL2
until you reach both ends.x
to node p
’s value. If p
has reached the end of LL1
, set to 0
.y
to node q
’s value. If q
has reached the end of LL2
, set to 0
.sum = x + y + carry
.carry = sum / 10
.sum mod 10
) and set it to current node’s next, then advance current node to next.p
and q
.carry = 1
, if so append a new node with digit 1 to the returning list.Note that we use a dummy head to simplify the code. Without a dummy head, you would have to write extra conditional statements to initialize the head’s value.
Take extra caution of the following cases:
Test Case | Explanation |
---|---|
l1=[0,1] l2=[0,1,2] | When one list is longer than the other. |
l1=[] l2=[0,1] | When one list is null, which means an empty list. |
l1=[9,9] l2=[1] | The sum could have an extra carry of one at the end, which is easy to forget. |
Java Code:
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode p = l1, q = l2, curr = dummyHead;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (p != null) p = p.next;
if (q != null) q = q.next;
}
if (carry > 0) {
curr.next = new ListNode(carry);
}
return dummyHead.next;
}
Time complexity : O(max(m,n)). Assume that mm and nn represents the length of l1 and l2 respectively, the algorithm above iterates at most max(m,n) times.
Space complexity : O(max(m,n)). The length of the new list is at most max(m,n)+1.
What if the the digits in the linked list are stored in non-reversed order? For example:
(3→4→2)+(4→6→5)=8→0→7
We can create a loop that goes through an element from both of the provided inputs, starting from the first/root element & end the loop when both the element’s “next” node points to a null. In each iteration of the loop, we can add the values & set that to the result node (if it’s the first iteration) or set it to the result’s next node in the list.
Time: Since we go over both the lists once, the time complexity will be O(n) where n is the larger of the two lists (in terms of the number of elements). Space: We will require constant space for the temporary variables, but the space required for the result will increase with the inputs.
On 04/03/2019:
Runtime: 19 ms, faster than 99.90% of Java online submissions for Add Two Numbers. Memory Usage: 47.8 MB, less than 41.96% of Java online submissions for Add Two Numbers.