Insert Greatest Common Divisors in Linked List - Problem

You're given the head of a linked list where each node contains an integer value. Your task is to enhance this linked list by inserting new nodes between every pair of adjacent nodes.

Each new node should contain the Greatest Common Divisor (GCD) of the two adjacent nodes it sits between. The GCD is the largest positive integer that divides both numbers evenly.

Goal: Return the modified linked list after all GCD insertions.

Example: If you have nodes with values [18, 6, 10, 3], you'll insert GCD nodes to get [18, 6, 6, 2, 10, 1, 3] because:

  • GCD(18, 6) = 6
  • GCD(6, 10) = 2
  • GCD(10, 3) = 1

Input & Output

example_1.py โ€” Basic case
$ Input: head = [18, 6, 10, 3]
โ€บ Output: [18, 6, 6, 2, 10, 1, 3]
๐Ÿ’ก Note: GCD(18,6)=6, GCD(6,10)=2, GCD(10,3)=1. Insert these values between respective pairs.
example_2.py โ€” Two nodes
$ Input: head = [7]
โ€บ Output: [7]
๐Ÿ’ก Note: Only one node exists, so no adjacent pairs to insert GCD between. Return original list.
example_3.py โ€” Same values
$ Input: head = [12, 12, 12]
โ€บ Output: [12, 12, 12, 12, 12]
๐Ÿ’ก Note: GCD(12,12)=12 for both pairs. Insert 12 between each adjacent pair of 12s.

Constraints

  • The number of nodes in the list is in the range [1, 5000]
  • 1 โ‰ค Node.val โ‰ค 1000
  • All node values are positive integers

Visualization

Tap to expand
City 18Toll 6City 6Toll 2City 10Highway with GCD Toll BridgesGCD(18,6)=6GCD(6,10)=2Euclidean Algorithm: gcd(a,b) = gcd(b, a mod b)Time: O(n * log min(a,b)) | Space: O(1)
Understanding the Visualization
1
Start Journey
Begin at the first city (head node) and prepare to visit adjacent city pairs
2
Calculate Toll
For each pair of cities, use the Euclidean algorithm to find their GCD efficiently
3
Build Bridge
Construct a toll bridge (new node) between the cities with the calculated GCD value
4
Continue Path
Move to the next original city, skipping the newly built bridge, and repeat the process
Key Takeaway
๐ŸŽฏ Key Insight: The Euclidean algorithm makes GCD calculation extremely efficient, allowing us to solve this linked list problem optimally in a single pass while maintaining the list structure.
Asked in
Google 25 Meta 18 Amazon 15 Microsoft 12
28.5K Views
Medium Frequency
~15 min Avg. Time
850 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