Ctrl K

GCD Between Neighbours

Medium
You are given the head of a singly linked list of positive integers. Between every two adjacent nodes, insert a new node whose value is the greatest common divisor of those two neighbours. Insertions go only between the original nodes; the new nodes are not paired with anything. Return the head of the resulting list.
Example 1
head=list_node([12, 8, 9]) → [12, 4, 8, 1, 9]

gcd(12, 8) = 4 and gcd(8, 9) = 1.

Example 2
head=list_node([5, 25, 25]) → [5, 5, 25, 25, 25]

gcd(5, 25) = 5 and gcd(25, 25) = 25.

Example 3
head=list_node([42]) → [42]

No neighbours, so the list stays as it is.

Constraints
  • The list has between 1 and 5000 nodes
  • 1 ≤ Node.val ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsAdding Digit Lists MediumPrimes Below a Bound MediumAdd One to a Digit Chain MediumForward Digit List Sum MediumLaser in a Mirror Room Medium
loading Python…
Input
head=list_node([12, 8, 9])
Expected
[12, 4, 8, 1, 9]

Run checks the first 3 tests in your browser. Submit checks all 117 tests on the server, hidden ones included.