◀ THE GRIND — MATH & GEOMETRY

Insert Greatest Common Divisors in Linked List

The drill: Between every pair of neighbouring nodes, splice in a new node holding their greatest common divisor — the original nodes keep their order, just with a gcd node wedged between each original pair.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

A singly linked list of positive integers arrives, and the task is to thread a brand-new node between every pair of neighbors already in that list.

Each inserted node holds the greatest common divisor of the two original values sitting immediately on either side of it — the original nodes keep their relative order and their own values untouched; only new nodes get woven in between them.

The result is the same head, now pointing through an alternating chain of original and inserted nodes — original, gcd, original, gcd, and so on — ending on whatever the last original node was.

EX 01
head = [2, 4]
[2, 2, 4]
TWO NODES, ONE INSERTION
EX 02
head = [7]
[7]
SINGLE NODE, NOTHING TO INSERT
EX 03
head = [9, 6, 3]
[9, 3, 6, 3, 3]
GCD SHIFTS AS THE WALK CONTINUES
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Every new node depends only on two original neighbours, and inserting one never disturbs a pair further down the list — so this can be done in a single left-to-right walk, no lookahead into already-modified structure needed.

HINT 2 THE STRUCTURE

The slow part is usually the gcd itself: counting down from the smaller value and testing divisibility works, but it's a linear scan for a number that Euclid's algorithm collapses to a handful of remainder steps.

HINT 3 ONE STEP FROM THE ANSWER

At each node, compute gcd(node.val, node.next.val) with repeated remainder (a, b) → (b, a mod b) until b hits 0, build a node holding it, splice it in between, then jump past the new node to continue at the original next node.

COACH'S BOARD — THE PATTERN, STEP BY STEP
EUCLID, SPLICED IN PLACEPATTERN · LINKED LIST — SPLICE GCDhead = 9 → 6 → 3
9
6
3
STEP 1

List 9 → 6 → 3. Walk pairs left to right, splicing a new gcd node between each original pair.

STEP 1 / 5 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/insert-greatest-common-divisors-in-linked-list.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def insertGreatestCommonDivisors(self, head: Optional[ListNode]) -> Optional[ListNode]:
        def gcd(a: int, b: int) -> int:
            while b:
                a, b = b, a % b
            return a

        cur = head
        while cur and cur.next:
            g = gcd(cur.val, cur.next.val)
            node = ListNode(g)
            node.next = cur.next
            cur.next = node
            cur = node.next   # skip past the inserted node to the original next
        return head
TIME O(N · LOG(MAXVAL))SPACE O(1) EXTRAPYTHON · RACE PACE · 15 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED