Problem Description
Given two non-empty linked lists representing two non-negative integers where the digits are stored in reverse order, calculate their sum and return it as a linked list. Each node in the list contains a single digit. The two numbers do not have any leading zeros (except the number 0).
Key Insights
- The digits are stored in reverse order, meaning the first node is the least significant digit.
- A carry may need to propagate through subsequent nodes.
- The two linked lists might be of different lengths.
- Continue processing until both lists are fully traversed and any remaining carry is handled.
Space and Time Complexity
Time Complexity: O(max(n, m)), where n and m are the lengths of the two linked lists. Space Complexity: O(max(n, m) + 1) for the result list in the worst case.
Solution
The solution iterates through both linked lists node by node. For each pair of corresponding nodes, their values and any carry from the previous operation are summed. The result is decomposed into a current digit (modulo 10) and an updated carry (total divided by 10). A new node is created for the current digit and appended to the resulting linked list. This process continues until all nodes are processed and any leftover carry is added as a final node.