Insert Greatest Common Divisors in Linked List (LeetCode 2807): Solution and Explanation
Given the head of a linked list of positive integers, insert between every two adjacent nodes a new node holding their greatest common divisor, and return the head.
Intuition
Each new value depends only on the two original nodes on either side of it. Nothing later in the list affects it, so a single left-to-right walk can do every insertion.
The gcd itself comes from Euclid's algorithm: gcd(a, b) = gcd(b, a % b), and gcd(a, 0) = a. The remainders shrink fast, so this takes only a handful of steps for values up to 1000.
Inserting after node is one assignment: node.next = ListNode(g, node.next). The new node takes over the old next pointer, so nothing is lost.
The one trap is the step forward. After inserting, node.next is the new gcd node, so the walk must jump two nodes to reach the next original node.
Approach: Single pass with Euclid's algorithm
- Set
node = head. - While
node.nextis not null, leta = node.valandb = node.next.val. - Repeat
a, b = b, a % buntilbis 0;ais the gcd. - Insert with
node.next = ListNode(a, node.next), then movenode = node.next.next. - Return
head.
Step-by-step example
head = [18,6,10,3]
- Pair (18, 6): 18 % 6 = 0, so the gcd is 6. Insert 6 between them and jump to the original 6.
- Pair (6, 10): 6 % 10 = 6, then 10 % 6 = 4, 6 % 4 = 2, 4 % 2 = 0. The gcd is 2. Insert it and jump to 10.
- Pair (10, 3): 10 % 3 = 1, then 3 % 1 = 0. The gcd is 1. Insert it and jump to 3.
- 3 has no next node, so the walk stops. Return [18,6,6,2,10,1,3].
Code: Python, Java, C++
1class Solution:
2 def insertGreatestCommonDivisors(self, head: Optional[ListNode]) -> Optional[ListNode]:
3 node = head
4 while node.next:
5 a, b = node.val, node.next.val
6 while b:
7 a, b = b, a % b
8 node.next = ListNode(a, node.next)
9 node = node.next.next
10 return head1class Solution {
2 public ListNode insertGreatestCommonDivisors(ListNode head) {
3 ListNode node = head;
4 while (node.next != null) {
5 int a = node.val, b = node.next.val;
6 while (b != 0) {
7 int t = a % b;
8 a = b;
9 b = t;
10 }
11 node.next = new ListNode(a, node.next);
12 node = node.next.next;
13 }
14 return head;
15 }
16}1class Solution {
2public:
3 ListNode* insertGreatestCommonDivisors(ListNode* head) {
4 ListNode* node = head;
5 while (node->next) {
6 int a = node->val, b = node->next->val;
7 while (b != 0) {
8 int t = a % b;
9 a = b;
10 b = t;
11 }
12 node->next = new ListNode(a, node->next);
13 node = node->next->next;
14 }
15 return head;
16 }
17};Time and space complexity
O(n log M)
There are n - 1 pairs and Euclid's algorithm takes O(log M) steps for values up to M = 1000.
O(1)
Apart from the n - 1 nodes the problem asks us to create, only a few variables are used.
Other approaches
Built-in gcd (time O(n log M), space O(1))
Use math.gcd in Python, std::gcd in C++ or BigInteger.gcd in Java instead of writing the loop. Same complexity, shorter code.
Trial division gcd (time O(n M), space O(1))
Try every divisor from min(a, b) down to 1 and take the first that divides both. Fine for values up to 1000, but O(M) per pair instead of O(log M).
Common mistakes
- Moving only one step after an insertion. The walk then pairs the new gcd node with the next original node and keeps inserting forever.
- Building the new node with
next = nullinstead ofnode.next, which cuts off the rest of the list. - Looping on
nodeinstead ofnode.next. The last original node has no partner and must not get a node after it. - Writing Euclid with the roles swapped, such as
b % a, which still terminates but takes an extra step and is easy to get wrong when one value is 0.
Frequently asked questions
Why does Euclid's algorithm work?
Any number that divides both a and b also divides a - k*b for every k, and in particular a % b. So the pairs (a, b) and (b, a % b) share exactly the same divisors and the same gcd.
Does the order of a and b matter?
No. If a is smaller than b, the first step a % b leaves a unchanged and simply swaps the pair, after which the algorithm continues normally.
What happens with a single node?
node.next is null from the start, so the loop never runs and the one-node list is returned unchanged.