Insert Greatest Common Divisors in Linked List — LeetCode 2807 Python Solution

MediumLinked ListMathNumber Theory
Problem
#2807
Reading time
3 min

The problem

Given the head of a linked list head, in which each node contains an integer value. Between every pair of adjacent nodes, insert a new node with a value equal to the greatest common divisor of them.

Example

Input
head = [18,6,10,3]
Output
[18,6,6,2,10,1,3]
Explanation
The 1st diagram denotes the initial linked list and the 2nd diagram denotes the linked list after inserting the new nodes (nodes in blue are the inserted nodes).

Python solution

Python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def insertGreatestCommonDivisors(
        self, head: Optional[ListNode]
    ) -> Optional[ListNode]:
        pre, cur = head, head.next
        while cur:
            x = gcd(pre.val, cur.val)
            pre.next = ListNode(x, cur)
            pre, cur = cur, cur.next
        return head

Complexity

MeasureComplexity
TimeO(n \times \log M), where n is the length of the linked list, and M is the maximum value of the nodes in the linked list
SpaceO(1) auxiliary

Pattern: Linked List

Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 2807. Insert Greatest Common Divisors in Linked List is filed here because LeetCode tags it Linked List, which is the vocabulary this hub collects.

The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2807. Insert Greatest Common Divisors in Linked List?
LeetCode 2807. Insert Greatest Common Divisors in Linked List is rated Medium on LeetCode.
What is the time complexity of LeetCode 2807. Insert Greatest Common Divisors in Linked List?
The Python solution on this page runs in O(n \times \log M), where n is the length of the linked list, and M is the maximum value of the nodes in the linked list.
What is the space complexity of LeetCode 2807. Insert Greatest Common Divisors in Linked List?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2807. Insert Greatest Common Divisors in Linked List cover?
LeetCode 2807. Insert Greatest Common Divisors in Linked List is tagged Linked List, Math and Number Theory on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview