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
Insert Greatest Common Divisors in Linked ListOriginal List:186103After Inserting GCD Values:186621013GCD(18,6)=6GCD(6,10)=2GCD(10,3)=1Green nodes are the inserted GCD values
Understanding the Visualization
1
Input
Linked list: 18 → 6 → 10 → 3
2
Process
Calculate GCD for each adjacent pair and insert
3
Output
Result: 18 → 6 → 6 → 2 → 10 → 1 → 3
Key Takeaway
🎯 Key Insight: Traverse once and use Euclidean algorithm for efficient GCD calculation while inserting nodes
Asked in
Google 25 Microsoft 18 Amazon 15
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen