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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code