SDE & MLE Prep

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