Problem Description
Given the head of a linked list where each node contains an integer, between every pair of adjacent nodes, insert a new node with a value equal to the greatest common divisor (GCD) of the values in those two nodes. Return the modified linked list after the insertions.
Key Insights
- Compute the GCD for each adjacent pair of nodes in one traversal.
- Insert the new node immediately between the two nodes.
- Since the linked list is traversed once, the solution is efficient.
- Use the properties of the GCD function to streamline the process.
Space and Time Complexity
Time Complexity: O(n * log(max(a, b))) where n is the number of nodes and log(max(a, b)) is the complexity of each GCD computation. Space Complexity: O(1) (ignoring the output list space)
Solution
The solution involves iterating over the linked list exactly once. For each pair of adjacent nodes:
- Compute the GCD of the numbers stored in the current node and the next node.
- Create a new node with the computed GCD value.
- Insert the new node between the current node and the next node.
- Advance the pointer to the next original node (skipping over the inserted node). This algorithm uses constant extra space while modifying the linked list in place. The key challenge is correctly handling node pointers to avoid breaking the list structure during insertion.