FunctionRacerProblemsRace

Insert GCD Between Neighbors

EasyLinked listsPython, JavaScript, TypeScript, Java, C++

Between every two neighboring nodes, insert a new node holding the greatest common divisor of their two values (the largest number that divides both). For 18 -> 6 -> 10 the answer is 18 -> 6 -> 6 -> 2 -> 10. Return the head. The list is passed in as head.

Linked lists appear in the tests as the list of their values, like [1,2,3]. Each node is a ListNode with .val and .next; the class is already defined for you.

Example 1

head [18,6,10]
returns [18,6,6,2,10]

gcd(18,6) = 6 and gcd(6,10) = 2.

Example 2

head [7]
returns [7]

No neighbors.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Linked lists problems