Insert Greatest Common Divisors in Linked List (LeetCode 2807): Solution and Explanation

Medium
Linked List
Math
Number Theory

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

  1. Set node = head.
  2. While node.next is not null, let a = node.val and b = node.next.val.
  3. Repeat a, b = b, a % b until b is 0; a is the gcd.
  4. Insert with node.next = ListNode(a, node.next), then move node = node.next.next.
  5. Return head.

Step-by-step example

head = [18,6,10,3]
  1. Pair (18, 6): 18 % 6 = 0, so the gcd is 6. Insert 6 between them and jump to the original 6.
  2. 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.
  3. Pair (10, 3): 10 % 3 = 1, then 3 % 1 = 0. The gcd is 1. Insert it and jump to 3.
  4. 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 head
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n log M)

There are n - 1 pairs and Euclid's algorithm takes O(log M) steps for values up to M = 1000.

Space

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 = null instead of node.next, which cuts off the rest of the list.
  • Looping on node instead of node.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.