702924. Make Co-prime Array

Basic

Here is a detailed markdown blog post for the "Make Co-prime Array" problem:

Make Co-prime Array

Summary

Given an array nums of integers, return a new array coPrimes where each element is either 0 or 1 indicating whether the corresponding element in nums is co-prime with all previously seen elements. A number x is said to be co-prime with another number y if their greatest common divisor (GCD) is 1.

Detailed Explanation

To solve this problem, we can iterate through the array and maintain a set of prime numbers seen so far. For each element in the array, check if it's co-prime with all previously seen elements by calculating the GCD using the Euclidean algorithm. If the GCD is 1, add the current element to the coPrimes array.

Here's a step-by-step breakdown of the solution:

View on GeeksforGeeks
public int[] makeCoprimeArray(int[] nums) {
    List<Integer> coPrimes = new ArrayList<>();
    Set<Integer> seenPrimes = new HashSet<>();

    for (int num : nums) {
        boolean isCoPrime = true;
        for (int prime : seenPrimes) {
            if (gcd(num, prime) != 1) {
                isCoPrime = false;
                break;
            }
        }
        if (isCoPrime) {
            coPrimes.add(1);
        } else {
            coPrimes.add(0);
        }

        if (num > 1) { // check if the number is prime
            for (int i = 2; i <= Math.sqrt(num); i++) {
                if (num % i == 0) {
                    seenPrimes.add(i);
                    break;
                }
            }
        }
    }

    int[] result = new int[coPrimes.size()];
    for (int i = 0; i < coPrimes.size(); i++) {
        result[i] = coPrimes.get(i);
    }
    return result;
}

private int gcd(int a, int b) {
    if (b == 0) {
        return a;
    } else {
        return gcd(b, a % b);
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.