Skip to content
Problem 2807 · LeetCode 2807(opens in a new tab)

Insert Greatest Common Divisors in Linked List

MediumLinked lists

A linked list starts at head, and every node stores a positive whole number. For each two nodes that sit next to each other, add a new node between them. Its value is the greatest common divisor (gcd) of the two values: the largest number that divides both with no remainder.

Only the original pairs get a new node; the new nodes do not make pairs of their own. Return the head of the longer list.

Example 1

Input:  head = [12, 8, 5]
Output: [12, 4, 8, 1, 5]
Why:    gcd(12, 8) = 4 and gcd(8, 5) = 1
2 more examples and the constraints

Example 2

Input:  head = [9]
Output: [9]
Why:    a single node has no neighbour

Example 3

Input:  head = [6, 6, 15]
Output: [6, 6, 6, 3, 15]
Why:    gcd(6, 6) = 6 and gcd(6, 15) = 3

Constraints

  • 1 ≤ number of nodes ≤ 5,000
  • 1 ≤ each node value ≤ 1,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Copy values, rebuildO(n log M)
  2. Splice in placeO(n log M)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeExtra memory for 5,000 nodesVerdict
Copy values, rebuildO(n log M)
Passes; copies everything
Splice in placeO(n log M)
Best; adds only the new nodes

n = number of nodes, M = largest value. Both do the same gcd work.

Edge cases to test

  • One node. [9] has no pair, so the list comes back unchanged.
  • Equal neighbours. gcd(6, 6) is 6 itself.
  • No shared factor. gcd(8, 5) is 1; the value 1 is always a common divisor.
  • A value of 1. Any pair that includes 1 gets a 1 in between.

Common mistakes

  • Advancing cur by one node, so the new gcd node gets paired with the next value.
  • Setting cur.next to the new node before saving the old next, which cuts off the rest of the list.
  • Computing gcd with a loop over every candidate divisor instead of Euclid.

How to talk through it

  1. 1Clarify. Do inserted nodes form new pairs? Can the list have a single node?
  2. 2Recall the gcd. Euclid: gcd(a, b) = gcd(b, a mod b), stopping when b is 0. It takes O(log M) steps.
  3. 3Give the simple way. Copy values into an array and rebuild the list with gcds in between.
  4. 4Splice in place. Insert after each original node and jump two ahead. Say why two.
  5. 5Test out loud. Run one node, equal neighbours, and a pair with gcd 1.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?