Insert Greatest Common Divisors in Linked List

Given the head of a linked list head, in which each node contains an integer value.

Between every pair of adjacent nodes, insert a new node with a value equal to the greatest common divisor of them.

Return the linked list after insertion.

The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.

Example 1
[18] -> [6] -> [10] -> [3] -> null
---
[18] -> [6] -> [6] -> [2] -> [10] -> [1] -> [3] -> null
Inputhead = [18,6,10,3]
Output[18,6,6,2,10,1,3]
We insert gcd values 6, 2, and 1 between each adjacent pair, then return the resulting linked list.
Example 2
[7] -> null
---
[7] -> null
Inputhead = [7]
Output[7]
There are no pairs of adjacent nodes, so we return the initial linked list.

Constraints

  • The number of nodes in the list is in the range [1, 5000].
  • 1 <= Node.val <= 1000

Asked at 5 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate