Insert Greatest Common Divisors in Linked List

medium linked list math gcd

Problem

Given the head of a linked list, insert between every pair of adjacent nodes a brand-new node whose value is the greatest common divisor (GCD) of those two neighboring values. The GCD of two numbers is the largest integer that divides both of them. Return the head of the modified list.

Inputhead = [18, 6, 10, 3]
Output[18, 6, 6, 2, 10, 1, 3]
gcd(18, 6) = 6, gcd(6, 10) = 2, gcd(10, 3) = 1 — each is spliced between its pair.

def insert_gcd(head):
    cur = head
    while cur.next:
        a, b = cur.val, cur.next.val
        g = gcd(a, b)
        node = ListNode(g)
        node.next = cur.next
        cur.next = node
        cur = node.next
    return head

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a
function insertGcd(head) {
  let cur = head;
  while (cur.next) {
    const g = gcd(cur.val, cur.next.val);
    const node = { val: g, next: cur.next };
    cur.next = node;
    cur = node.next;
  }
  return head;
}

function gcd(a, b) {
  while (b) { [a, b] = [b, a % b]; }
  return a;
}
class Solution {
    public ListNode insertGreatestCommonDivisors(ListNode head) {
        ListNode cur = head;
        while (cur.next != null) {
            int g = gcd(cur.val, cur.next.val);
            ListNode node = new ListNode(g);
            node.next = cur.next;
            cur.next = node;
            cur = node.next;
        }
        return head;
    }

    private int gcd(int a, int b) {
        while (b != 0) { int t = a % b; a = b; b = t; }
        return a;
    }
}
ListNode* insertGreatestCommonDivisors(ListNode* head) {
    ListNode* cur = head;
    while (cur->next != nullptr) {
        int g = gcd(cur->val, cur->next->val);
        ListNode* node = new ListNode(g);
        node->next = cur->next;
        cur->next = node;
        cur = node->next;
    }
    return head;
}

int gcd(int a, int b) {
    while (b != 0) { int t = a % b; a = b; b = t; }
    return a;
}
Time: O(n log M) Space: O(1) extra (excluding inserted nodes)