Insert Greatest Common Divisors in Linked List

You are given the head of a linked list whose nodes hold integers. Between every pair of adjacent nodes, insert a new node whose value is the greatest common divisor of the two. Return the head of the resulting list.

30:00

Insert Greatest Common Divisors in Linked List
medium
Free written solution
Topics
Companies

You are given the head of a linked list whose nodes hold integers. Between every pair of adjacent nodes, insert a new node whose value is the greatest common divisor of the two. Return the head of the resulting list.

Example 1:
Input: {"head":[18,6,10,3]}
Output: [18,6,6,2,10,1,3]
Constraints:
  • The number of nodes in the list is in the range [1,5000][1, 5000].

  • 1≤Node.val≤10001 \leq \text{Node.val} \leq 1000

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"head":[18,6,10,3]}

Walk the 4 original nodes. Between every adjacent pair, insert a new node holding their greatest common divisor, found with Euclid's algorithm.

■ node (a)■ node.next (b)■ inserted gcd node
186103null

Euclid's algorithm: (a, b) → (b, a % b) until b = 0

Waiting for the first pair.

Variables
VariableValue
node18
a-
b-
inserted0
DepthFunction Call
Stack empty
0/15