Given two non-negative integers represented as linked lists with heads head1 and head2, where each node contains a single digit, return a new linked list representing their sum.
Note: The input lists may contain leading zeros, but the resulting sum list must not contain any leading zeros.
[Naive Approach] By creating a new list - O(m + n) Time and O(max(m, n)) Space
To sum two linked lists, start by creating an empty linked list, say result, for the sum. Reverse both original linked lists to start from the least significant digit.
Use two pointers to traverse the reversed lists simultaneously. For each pair of nodes, compute their sum and if the sum exceeds 9, store the remainder (sum modulo 10) in the new node and forward the carry to the next pair of nodes. Append each new node to result.
Continue until both lists are fully traversed, handling any remaining nodes from the longer list and carrying over any final carry. Finally, reverse the result linked list to get the sum of the two linked list.
Output
1 -> 1 -> 2 -> 2
[Expected Approach] By storing sum on the longer list - O(m + n) Time and O(1) Space
The idea is to first reverse both linked lists so that addition can be performed starting from the least significant digit. We then iterate through both lists simultaneously, adding corresponding digits along with any carry. For each sum, we create a new node and insert it at the front of the result list.
After processing all nodes, if a carry remains, we add a new node for it. Finally, the resulting list represents the sum without any leading zeros.
Illustrations:
Output
1 -> 1 -> 2 -> 2
[Other Approach] Using Recursion - O(m + n) Time and O(max(m, n)) Space
The idea is to use recursionto compute the sum. Recursively move to the end of the lists, calculate the sum of the last nodes (including any carry from previous additions), while backtracking add up the sums together.