Insert Greatest Common Divisors in Linked List - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
head = [18,6,10,3]
›
Output:
[18,6,6,2,10,1,3]
💡 Note:
GCD(18,6)=6, insert 6. GCD(6,10)=2, insert 2. GCD(10,3)=1, insert 1. Result: [18,6,6,2,10,1,3]
Example 2 — Two Nodes
$
Input:
head = [7]
›
Output:
[7]
💡 Note:
Single node, no adjacent pairs exist, so no insertions needed
Example 3 — Coprime Numbers
$
Input:
head = [7,11,13]
›
Output:
[7,1,11,1,13]
💡 Note:
GCD(7,11)=1, GCD(11,13)=1. Prime numbers are coprime, so GCD is always 1
Constraints
- The number of nodes in the list is in the range [1, 5000]
- 1 ≤ Node.val ≤ 1000
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code