
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.
1import java.util.HashMap;
2
3public class Solution {
4 private int gcd(int a, int b) {
5 while (b != 0) {
6 int temp = b;
7 b = a % b;
8 a = temp;
9 }
10 return a;
11 }
12
13 public boolean hasGroupsSizeX(int[] deck) {
14 HashMap<Integer, Integer> freq = new HashMap<>();
15 for (int num : deck) {
16 freq.put(num, freq.getOrDefault(num, 0) + 1);
17 }
18
19 int X = 0;
20 for (int count : freq.values()) {
21 X = gcd(X, count);
22 }
23
24 return X > 1;
25 }
26
27 public static void main(String[] args) {
28 Solution sol = new Solution();
29 int[] deck = {1,2,3,4,4,3,2,1};
30 System.out.println(sol.hasGroupsSizeX(deck) ? "true" : "false");
31 }
32}This Java solution applies a similar strategy: it uses a HashMap for counting, then checks the GCD of the counts. The necessary calculations follow after considering all unique counts.
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.