Input: head =[18,6,10,3]Output: [18,6,6,2,10,1,3]Explanation: The 1st diagram denotes the initial linked list and the 2nd diagram denotes the linked list after inserting the newnodes(nodes in blue are the inserted nodes).- We insert the greatest common divisor of 18 and 6=6 between the 1st and the 2nd nodes.- We insert the greatest common divisor of 6 and 10=2 between the 2nd and the 3rd nodes.- We insert the greatest common divisor of 10 and 3=1 between the 3rd and the 4th nodes.There are no more adjacent nodes, so we return the linked list.
Example 2:
1
2
3
4
Input: head =[7]Output: [7]Explanation: The 1st diagram denotes the initial linked list and the 2nd diagram denotes the linked list after inserting the new nodes.There are no pairs of adjacent nodes, so we return the initial linked list.
classSolution {
public ListNode insertGreatestCommonDivisors(ListNode head) {
if (head ==null|| head.next==null) {
return head;
}
ListNode curr = head;
while (curr !=null&& curr.next!=null) {
ListNode next = curr.next;
int gcdVal = gcd(curr.val, next.val);
// Create new node with the GCD value ListNode gcdNode =new ListNode(gcdVal);
gcdNode.next= next;
curr.next= gcdNode;
// Move to the next pair curr = next;
}
return head;
}
// Method to calculate GCD using Euclidean algorithmprivateintgcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
}
classSolution:
defgcd(self, a: int, b: int) -> int:
while b:
a, b = b, a % b
return a
definsertGreatestCommonDivisors(
self, head: Optional[ListNode]
) -> Optional[ListNode]:
ifnot head ornot head.next:
return head
curr = head
while curr and curr.next:
next = curr.next
gcd_val = self.gcd(curr.val, next.val)
# Create new node with the GCD value gcd_node = ListNode(gcd_val)
gcd_node.next = next
curr.next = gcd_node
# Move to the next pair curr = next
return head
⏰ Time complexity: O(n), where n is the number of nodes in the linked list. Each node is visited once, and the GCD calculation adds a negligible amount of additional time per node.
🧺 Space complexity: O(1), additional space, not counting the space used by the new nodes created and the input/output linked list.