Find the size of largest group where groups are according to the xor of digits

Given an integer N and the task is to find the size of the largest group in a range 1 to N, where two numbers belong to the same group if xor of its digits is same.

Examples:

Input: N = 13
Output: 2
Explanation:
There are 10 groups in total, they are grouped according to the xor of its digits of numbers from 1 to 13: [11] [1, 10] [2, 13] [3, 12] [4] [5] [6] [7] [8] [9].
Out of these, 3 groups have the largest size that is 2.

Input: N = 2
Output: 1
Explanation:
There are 2 groups in total, they are grouped according to the xor of its digits of numbers from 1 to 2: [1] [2].
Out of these, both groups have the largest size that is 1.

Approach:



To solve the problem mentioned above we have to store the xor of digit of every element from 1 to N using hash map and increment its frequency if it repeats. Then find the maximum frequency within the hash map, which would be the largest size of the group. And finally, count all the groups who have the same frequency count as the largest group and return the count.

Below is the implementation of above the approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// c++ implementation to Find the
// size of largest group, where groups
// are according to the xor of its digits.
#include <bits/stdc++.h>
using namespace std;
  
// Function to find out xor of digit
int digit_xor(int x)
{
    int xorr = 0;
  
    // calculate xor digitwise
    while (x) {
        xorr ^= x % 10;
        x = x / 10;
    }
  
    // return xor
    return xorr;
}
  
// Function to find the
// size of largest group
int find_count(int n)
{
    // hash map for counting frquency
    map<int, int> mpp;
  
    for (int i = 1; i <= n; i++) {
  
        // counting freq of each element
        mpp[digit_xor(i)] += 1;
    }
  
    int maxm = 0;
    for (auto x : mpp) {
        // find the maximum
        if (x.second > maxm)
  
            maxm = x.second;
    }
  
    return maxm;
}
  
// Driver code
int main()
{
    // initialise N
    int N = 13;
  
    cout << find_count(N);
  
    return 0;
}

chevron_right


Output:

2

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.