Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Find Greatest Common Divisor of Array

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1979" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

Given an integer array nums, return the greatest common divisor of the smallest number and largest number in nums. The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers. Example 1: Input: nums = [2,5,6,9,10] Output: 2 Explanation: The smallest number in nums is 2. The largest number in nums is 10. The greatest common divisor of 2 and 10 is 2. Example 2: Input: nums = [7,5,6,8,3] Output: 1 Explanation: The smallest number in nums is 3. The largest number in nums is 8. The greatest common divisor of 3 and 8 is 1. Example 3: Input: nums = [3,3] Output: 3 Explanation: The smallest number in nums is 3. The largest number in nums is 3. The greatest common divisor of 3 and 3 is 3. Constraints: 2 <= nums.length <= 1000 1 <= nums[i] <= 1000

Explanation

Here's an efficient solution to find the greatest common divisor (GCD) of the smallest and largest numbers in an integer array:

  • Find Min/Max: Iterate through the array once to find the smallest and largest numbers.
  • GCD Calculation: Use the Euclidean algorithm to efficiently compute the GCD of the found minimum and maximum values.
  • Return GCD: Return the calculated GCD.

  • Runtime Complexity: O(N + log(max(a, b))), where N is the length of the input array and a, b are the minimum and maximum numbers respectively. The O(N) comes from iterating the array to find the minimum and maximum and the O(log(max(a, b))) is from applying the Euclidean Algorithm. Storage Complexity: O(1)

Code

    def findGCD(nums):
    """
    Finds the greatest common divisor of the smallest and largest numbers in an array.

    Args:
        nums: An integer array.

    Returns:
        The greatest common divisor of the smallest and largest numbers in nums.
    """

    min_num = nums[0]
    max_num = nums[0]

    for num in nums:
        min_num = min(min_num, num)
        max_num = max(max_num, num)

    def gcd(a, b):
        while(b):
            a, b = b, a % b
        return a

    return gcd(min_num, max_num)

More from this blog

C

Chatmagic blog

2894 posts