# Understanding Leetcode: Add Two Numbers (Medium)

Problem: Suppose you are given two non-empty linked lists representing two non-negative integers. The numbers are stored in reverse order, and each node is a single digit. Add the two numbers and return it as a linked list.

This problem is interesting due to it having a lot of moving parts. The best things to do with a problem like this is try a few examples first, so we can get an idea of what the problem is really asking, and what cases may come up.

First, let’s try the provided example:

Input 1: [2,4,3]

Input 2: [5,6,4]

You can see that in this example, our algorithm to calculate the answer is easy. We simply add each digit, keeping track of any carry that might occur. If there is a carry, we add it to the next digit. Once we reach the end of both digits, we are done. This is the easiest case of the problem, since both numbers are the same size, and carry doesn’t exceed the number of digits provided. Something slightly harder could be the following:

Input 1: [2,4,3]

Input 2: [8,0,8]

This is trickier since we end up with a number that has more digits than we started with. This is another situation we need to watch out for, if the number has carries beyond the digits calculated, we still need to consider it, otherwise our solution will be wrong. There is one final situation that we would want to consider for this problem:

Input 1: [2,2,3]

Input 2: [2,1]

In this case, we could have one number that is smaller than the other. We need to make sure that we keep track of whether we have iterated the whole of either list before we try to add a number from the list.

With these three scenarios in mind, let’s look at how we can implement a solution to this problem. To start, we are going to iterate the lists we are given until we have exhausted all the elements in both lists. To do this, we setup some tracker variables, i and j, to determine where we currently are in the list. If we have exceeded the length of either list, we simply set the current element for that list to 0 and keep adding 0 to the existing values. The loop looks like this: