![]() |
VOOZH | about |
Given n integers, we need to find size of the largest subset with GCD equal to 1.
Input Constraint : n <= 10^5, A[i] <= 10^5
Examples:
Input : A = {2, 3, 5}
Output : 3
Explanation: The largest subset with GCD equals to 1 is {2, 3, 5}, and the size of the subset is 3.
Input : A = {3, 18, 12}
Output : -1
Explanation: No subset of the array has a GCD equal to 1, so the output is -1.
We find GCD of all possible subsets and find the largest subset whose GCD is 1. Total time taken will be equal to the time taken to evaluate GCD of all possible subsets. Total possible subsets are 2n. In worst case there are n elements in subset and time taken to calculate its GCD will be n * log(n)
Extra space required to hold current subset is O(n)
Let say we find a subset with GCD 1, if we add a new element to it then GCD still remains 1. Hence if a subset exists with GCD 1 then GCD of the complete set is also 1. Hence we first find GCD of the complete set, if its 1 then complete set is that subset else no subset exist with GCD 1.
4
Time Complexity : O(n* log(n))
Space Complexity : O(1)