• Difficulty Level : Medium
• Last Updated : 15 Jul, 2021

Given two numbers represented by two linked lists, write a function that returns sum list. The sum list is linked list representation of addition of two input numbers. Expected Space Complexity O(1).

Examples:

Input:
L1 = 5 -> 6 -> 3 -> NULL
L2 = 8 -> 4 -> 2 -> NULL
Output: 1 -> 4 -> 0 -> 5 -> NULL

Input:
L1 = 1 -> 0 -> 0 -> NULL
L2 = 9 -> 1 -> NULL
Output: 1 -> 9 -> 1 -> NULL

Approach: We have discussed a solution here where we used recursion to reach to the least significant number in the lists, but due to the involvement of the stack, the space complexity of the solution becomes O(N)
Here the target is to do the sum inplace, and return the modified sum list.

The idea is to first reverse both the linked list, so new head of the list points to least significant number and we can start adding as described here and instead of creating a new list, we modify the existing one and return the head of modified list.

Following are the steps:

1. Reverse List L1.
2. Reverse List L2.
3. Add the nodes of both the lists iteratively.
4. Reverse the resultant list and return its head.

Below is the implementation of the above approach:

## Javascript



Output:

1 -> 4 -> 0 -> 5 -> NULL

Time Complexity: O(max(m, n)) where m and n are number of nodes in list l1 and list l2 respectively.
Space Complexity: O(1)

My Personal Notes arrow_drop_up