Skip to content
LC-2807 Medium LeetCode

2807. Insert Greatest Common Divisors in Linked List

Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 92% Topics: Linked List, Math, Number Theory
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(n)
# Space: O(1)

# linked list
class Solution(object):
    def insertGreatestCommonDivisors(self, head):
        """
        :type head: Optional[ListNode]
        :rtype: Optional[ListNode]
        """
        def gcd(a, b):
            while b:
                a, b = b, a%b
            return a

        curr = head
        while curr.next:
            curr.next = ListNode(gcd(curr.val, curr.next.val), curr.next)
            curr = curr.next.next
        return head

Solution from kamyu104/LeetCode-Solutions · MIT

Similar questions