X of a Kind in a Deck of Cards in C++

C++Server Side ProgrammingProgramming

Suppose we have a deck of cards, each card has an integer written on it. We have to check whether we can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where the following condition satisfies: Each group has exactly X number of cards. All of the cards in each group have the same number.

So, if the input is like deck = [1,2,3,4,4,3,2,1], then the output will be True, as possible partitions are [1,1],[2,2],[3,3],[4,4].

To solve this, we will follow these steps −

  • Define one map mp
  • for all x in deck
    • (increase mp[x] by 1)
  • for all key-value pair x in mp
    • ans := gcd of (ans and value of x)
  • return true when ans > 1, otherwise false

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   bool hasGroupsSizeX(vector<int>& deck) {
      unordered_map<int, int> mp;
      int ans;
      for (auto x : deck)
         mp[x]++;
      for (auto x : mp)
         ans = __gcd(ans, x.second);
      return (ans > 1);
   }
};
main(){
   Solution ob;
   vector<int> v = {1,2,3,4,4,3,2,1};
   cout << (ob.hasGroupsSizeX(v));
}

Input

{1,2,3,4,4,3,2,1}

Output

1
raja
Published on 04-Jul-2020 13:55:45
Advertisements