Skip to main content
LeetCode 2807, Medium. Topics: Linked List, Math, Number Theory. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 15 parametrized pytest cases, and a playground notebook:

Problem

Given the head of a linked list, return the list after inserting the greatest common divisor of each pair of adjacent nodes. Between every pair of adjacent nodes, insert a new node with a value equal to the greatest common divisor of them. The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.

Examples

Example 1
Example 2

Constraints

  • The number of nodes in the list is in the range [1, 5000].
  • 1 <= Node.val <= 1000

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode 250, NeetCode All.
Last modified on August 25, 2026