2807. Insert Greatest Common Divisors in Linked List - Explanation

Problem Link

Description

You are 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.

Return the head of the linked list after insertion.

The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.

Example 1:

Input: head = [12,3,4,6]

Output: [12,3,3,1,4,2,6]

Example 2:

Input: head = [2,1]

Output: [2,1,1]

Constraints:

  • 1 <= The length of the list <= 5000.
  • 1 <= Node.val <= 1000

Company Tags

Please upgrade to NeetCode Pro to view company tags.



1. Simulation

# 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]:
        def gcd(a, b):
            while b > 0:
                a, b = b, a % b
            return a

        cur = head
        while cur.next:
            n1, n2 = cur.val, cur.next.val
            cur.next = ListNode(gcd(n1, n2), cur.next)
            cur = cur.next.next

        return head

Time & Space Complexity

  • Time complexity: O(nlog(min(a,b)))O(n * \log (min(a, b)))
  • Space complexity:
    • O(n)O(n) space for the gcd ListNodes.
    • O(1)O(1) extra space.

Where nn is the length of the given list, and aa and bb are two numbers passed to the gcd()gcd() function.