Here's how I decided to solve it:
Step 1: Pass through both linked lists, find the lengths
say len(L1) = m and len(L2) = n
Step 2: Find the difference in lengths
if ( m > n ) d = m - n else if ( n > m ) d = n - m else d = 0
Step 3: Move the temporary pointer d in front of the large list
Step 4: Now we have two linked lists for adding, the length of which is the same, so add them recursively, supporting hyphenation.
Step 5: ( Note: if (d == 0) does not complete this step)
After step 4, we have a partial list of output, and now we need to put the remaining list from a larger list at the top of the list of results.
if ( d > 0 ) -Travel larger list till d positions recursively -Append sum = value_at_end + carry (update carry if sum >= 10) to output list at beginning -Repeat until difference is consumed
Note. I solve the problem because it is put before me, and not by suggesting a change in the underlying data structure.
Time complexity:
- Creating single passes in both lists to find their length:
O(m+n) - Recursive summation of two linked lists of equal size (m - d and n):
O(n) , assuming m > n - Adding the remaining list of a larger list to the output list:
O(d)
Total: O( (m+n) + (n) + (d) ) OR O(m+n)
The complexity of the space:
- time step 2:
O(n) , runtime stack space - step 3 of time complexity:
O(d) , runtime stack space
Total: O(n + d) OR O(n)
Rajendra uppal
source share