Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: GCD Sort of an Array

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1998" 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

You are given an integer array nums, and you can perform the following operation any number of times on nums: Swap the positions of two elements nums[i] and nums[j] if gcd(nums[i], nums[j]) > 1 where gcd(nums[i], nums[j]) is the greatest common divisor of nums[i] and nums[j]. Return true if it is possible to sort nums in non-decreasing order using the above swap method, or false otherwise. Example 1: Input: nums = [7,21,3] Output: true Explanation: We can sort [7,21,3] by performing the following operations: - Swap 7 and 21 because gcd(7,21) = 7. nums = [21,7,3] - Swap 21 and 3 because gcd(21,3) = 3. nums = [3,7,21] Example 2: Input: nums = [5,2,6,2] Output: false Explanation: It is impossible to sort the array because 5 cannot be swapped with any other element. Example 3: Input: nums = [10,5,9,3,15] Output: true We can sort [10,5,9,3,15] by performing the following operations: - Swap 10 and 15 because gcd(10,15) = 5. nums = [15,5,9,3,10] - Swap 15 and 3 because gcd(15,3) = 3. nums = [3,5,9,15,10] - Swap 10 and 15 because gcd(10,15) = 5. nums = [3,5,9,10,15] Constraints: 1 <= nums.length <= 3 * 104 2 <= nums[i] <= 105

Explanation

Here's the breakdown of the approach and the Python code:

  • High-Level Approach:

    • Factorize each number in the input array. Store the prime factors.
    • Use a Union-Find data structure to connect indices that share a common factor (i.e., their corresponding array elements can be swapped).
    • Check if the sorted version of the array can be obtained by swapping elements within the connected components identified by Union-Find.
  • Complexity:

    • Runtime: O(n * sqrt(M) + n log n), where n is the length of the input array and M is the maximum value in the input array.
    • Storage: O(n + sqrt(M))

Code

    def gcd_sort(nums):
    """
    Determines if an array can be sorted by swapping elements with gcd > 1.

    Args:
        nums: An integer array.

    Returns:
        True if the array can be sorted, False otherwise.
    """

    n = len(nums)
    parent = list(range(n))

    def find(i):
        if parent[i] == i:
            return i
        parent[i] = find(parent[i])
        return parent[i]

    def union(i, j):
        root_i = find(i)
        root_j = find(j)
        if root_i != root_j:
            parent[root_i] = root_j

    def get_prime_factors(num):
        factors = set()
        d = 2
        while d * d <= num:
            if num % d == 0:
                factors.add(d)
                while num % d == 0:
                    num //= d
            d += 1
        if num > 1:
            factors.add(num)
        return factors

    prime_index = {}
    for i in range(n):
        factors = get_prime_factors(nums[i])
        for factor in factors:
            if factor in prime_index:
                union(i, prime_index[factor])
            else:
                prime_index[factor] = i

    sorted_nums = sorted(nums)
    components = {}
    for i in range(n):
        root = find(i)
        if root not in components:
            components[root] = []
        components[root].append(nums[i])

    for root in components:
        components[root].sort()

    component_index = {}
    for i in range(n):
        root = find(i)
        if root not in component_index:
            component_index[root] = 0
        if nums[i] != sorted_nums[i]:
            root = find(i)
            if components[root][component_index[root]] != sorted_nums[i]:
                return False
        component_index[root] += 1

    return True

More from this blog

C

Chatmagic blog

2894 posts