# Check if frequency of each digit is less than the digit

Given an integer n, the task is to check if frequency of each digit of the number is less than or equal to digit itself.

Examples:

```Input : 51241
Output : False

Input : 1425243
Output : True
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Naive Approach: Start from 0 and count the frequency for every digit upto 9, if at any place frequency is more than the digit value then return false, else return true.

```// A C++ program to validate a number
#include<bits/stdc++.h>
using namespace std;

// Function to validate number (Check if
// frequency of a digit is less than the
// digit itself or not)
bool validate(long long int n)
{
for (int i=0; i<10; i++)
{
long long int temp = n;
int count = 0;
while (temp)
{
// If current digit of temp is
// same as i
if (temp % 10 == i)
count++;

// if frequency is greater than
// digit value, return false
if (count > i)
return false;

temp /= 10;
}
}
return true;
}

// driver program
int main()
{
long long int n = 1552793;
if (validate(n))
cout << "True";
else
cout << "False";
return 0;
}
```

Output:

```True
```

Efficient Approach: is to store the frequency of each digit and if at any place frequency is more than the digit value then return false, else return true.

```// A C++ program to validate a number
#include<bits/stdc++.h>
using namespace std;

// Function to validate number (Check if
// frequency of a digit is less than the
// digit itself or not)
bool validate(long long int n)
{
int count[10] = {0};
while (n)
{
// calculate frequency of each digit
int r = n % 10;

// If count is already r, then
// incrementing it would invalidate,
// hence we return false.
if (count[r] == r)
return false;

count[r]++;
n /= 10;
}

return true;
}

// driver program
int main()
{
long long int n = 1552793;
if (validate(n))
cout << "True";
else
cout << "False";
return 0;
}
```

Output:

```True
```

# GATE CS Corner    Company Wise Coding Practice

1.5 Average Difficulty : 1.5/5.0
Based on 6 vote(s)