2807. Insert Greatest Common Divisors in Linked List
Problem
Between every pair of adjacent nodes, insert a new node holding the greatest common divisor of their two values.
Example: 18→6→10→3 → 18→6→6→2→10→1→3
Walk the list; between each node and its successor splice in a new node holding gcd(a, b), then jump past it.
Complexity: O(n log V).
class Solution:
def insertGreatestCommonDivisors(self, head: Optional[ListNode]) -> Optional[ListNode]:
cur = head
while cur and cur.next:
cur.next = ListNode(math.gcd(cur.val, cur.next.val), cur.next)
cur = cur.next.next
return head
assert list_vals(Solution().insertGreatestCommonDivisors(make_list([18, 6, 10, 3]))) == [18, 6, 6, 2, 10, 1, 3]
assert list_vals(Solution().insertGreatestCommonDivisors(make_list([7]))) == [7]
assert list_vals(Solution().insertGreatestCommonDivisors(make_list([4, 4]))) == [4, 4, 4]
class Solution {
public ListNode insertGreatestCommonDivisors(ListNode head) {
for (ListNode cur = head; cur != null && cur.next != null; cur = cur.next.next)
cur.next = new ListNode(gcd(cur.val, cur.next.val), cur.next);
return head;
}
private int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
}
func insertGreatestCommonDivisors(head *ListNode) *ListNode {
gcd := func(a, b int) int {
for b != 0 {
a, b = b, a%b
}
return a
}
for cur := head; cur != nil && cur.Next != nil; cur = cur.Next.Next {
cur.Next = &ListNode{Val: gcd(cur.Val, cur.Next.Val), Next: cur.Next}
}
return head
}