Skip to contentKEEP THE CRAFTTHE SANCTUARY

Insert GCD Nodes in a Linked List

Insert a node holding the greatest common divisor between every pair of neighbors.

The problem

Implement Solution.insertGreatestCommonDivisors(head). Between every two adjacent nodes of the original list, insert a new node whose value is the greatest common divisor (the largest number that divides both) of those two values. Return head. For example, 18 -> 6 -> 10 -> 3 becomes 18 -> 6 -> 6 -> 2 -> 10 -> 1 -> 3. Keep the original nodes in place. The list has 1 to 5,000 nodes, and every value is between 1 and 1,000.

Starter code

class Solution:
    def insertGreatestCommonDivisors(self, head):
        pass

Public examples

  1. head = [18, 6, 10, 3]gives[18, 6, 6, 2, 10, 1, 3]
  2. head = [8, 3]gives[8, 1, 3]
  3. head = [5, 5]gives[5, 5, 5]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.