
Sponsored
Sponsored
This approach involves counting the frequency of each card number. Once we have the frequencies, the problem reduces to checking if there exists a number x greater than 1 that divides all these frequencies. This is efficiently achieved by calculating the GCD of the list of frequencies.
Time Complexity: O(n + m log m), where n is the length of the deck and m is the number of unique numbers.
Space Complexity: O(m), where m is the number of unique numbers due to the frequency array.
1from collections import Counter
2from math import gcd
3from functools import reduce
4
5def hasGroupsSizeX(deck):
6 def GCD(arr):
7 return reduce(gcd, arr)
8
9 count = Counter(deck)
10 return GCD(count.values()) > 1
11
12if __name__ == "__main__":
13 deck = [1,2,3,4,4,3,2,1]
14 print(hasGroupsSizeX(deck))This Python solution uses the `Counter` to tally frequencies quickly. It uses the math and functools libraries to calculate the GCD of all frequency counts to determine if a valid grouping is possible.
This approach also involves counting the frequency of each card in the deck. However, rather than immediately calculating the GCD, it sorts the frequency list and iteratively checks for the smallest divisor of these frequencies greater than 1.
Time Complexity: O(n + m√n), where n is the number of cards and m is the number of unique cards.
Space Complexity: O(m) for the frequency array.
1
This solution starts by counting frequencies and finding the smallest non-zero frequency. It attempts to divide all frequencies by each integer from 2 to `min_freq`. If successful, it returns true; otherwise, returns false.