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 GCD in Linked List INPUT Original Linked List: 18 6 10 3 NULL head = [18, 6, 10, 3] 4 nodes in linked list Adjacent pairs: (18,6) (6,10) (10,3) GCDs to insert: GCD(18,6)=6, GCD(6,10)=2, GCD(10,3)=1 ALGORITHM STEPS 1 Traverse List Start from head, check if next node exists 2 Euclidean GCD GCD(a,b) = GCD(b, a%b) until b becomes 0 3 Create GCD Node New node with GCD value between current pair 4 Insert and Link curr.next = gcdNode gcdNode.next = nextNode Euclidean Example: GCD(18,6) GCD(18, 6): 18 % 6 = 0 GCD(6, 0) = 6 GCD(6, 10): 10 % 6 = 4 6 % 4 = 2 4 % 2 = 0 Result: 2 Result: 6 FINAL RESULT Modified Linked List: 18 6 GCD 6 2 GCD 10 1 GCD 3 NULL Original Inserted Output: [18,6,6,2,10,1,3] OK - Verified! 3 GCD nodes inserted List size: 4 --> 7 Time: O(n * log(max)) Key Insight: The Euclidean Algorithm efficiently computes GCD by repeatedly replacing the larger number with the remainder of dividing both numbers. GCD(a,b) = GCD(b, a mod b) until remainder is 0. Time complexity is O(n * log(max_value)) where n is list length. Space is O(1) excluding output. TutorialsPoint - Insert Greatest Common Divisors in Linked List | Euclidean Algorithm
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