Given a number N the task is to check whether the frequency of each digit in a number is equal to its value or not
Examples:
Input: N = 3331
Output: Yes
Explanation: It is a valid number since frequency of 3 is 3, and frequency of 1 is 1
Input: N = 121
Output: No
Explanation: It is not a valid number since frequency of 1 is 2, and frequency of 2 is 1
Approach: The task can be solved by storing the frequencies of a digit in a hashmap and then iterating the hashmap to check whether the frequency of the digit is equal to its value or not.
Below is the implementation of the above approach:
C++14
#include <bits/stdc++.h>
using namespace std;
void check( int N)
{
unordered_map< char , int > occ;
while (N > 0) {
int r = N % 10;
occ[r]++;
N /= 10;
}
for ( auto i : occ) {
if (i.first != i.second) {
cout << "No\n" ;
return ;
}
}
cout << "Yes\n" ;
}
int main()
{
int N = 3331;
check(N);
return 0;
}
|
Java
import java.io.*;
import java.util.HashMap;
import java.util.Map;
class GFG
{
public static void check(Integer N)
{
HashMap<Integer, Integer> occ = new HashMap<>();
while (N > 0 ) {
Integer r = N % 10 ;
if (occ.containsKey(r)) {
occ.put(r, occ.get(r) + 1 );
}
else {
occ.put(r, 1 );
}
N = N / 10 ;
}
for (Map.Entry<Integer, Integer> e :
occ.entrySet()) {
if (e.getKey() != e.getValue()) {
System.out.print( "NO" );
return ;
}
}
System.out.print( "Yes" );
}
public static void main(String[] args)
{
Integer N = 3331 ;
check(N);
}
}
|
Python3
def check(N):
occ = dict ();
while (N > 0 ):
r = N % 10 ;
if r in occ:
occ[r] + = 1
else :
occ[r] = 1
N = N / / 10
for i in occ.keys():
if (i ! = occ[i]):
print ( "No" );
return ;
print ( "Yes" );
N = 3331 ;
check(N);
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public static void check( int N)
{
Dictionary< int , int > occ = new Dictionary< int , int >();
while (N > 0) {
int r = N % 10;
if (occ.ContainsKey(r)) {
occ[r] = occ[r] + 1;
}
else {
occ.Add(r, 1);
}
N = N / 10;
}
foreach ( int key in occ.Keys) {
if (key != occ[key]) {
Console.Write( "NO" );
return ;
}
}
Console.Write( "Yes" );
}
public static void Main()
{
int N = 3331;
check(N);
}
}
|
Javascript
<script>
function check(N) {
let occ = new Map();
while (N > 0) {
let r = N % 10;
if (occ.has(r)){
occ.set(r, occ.get(r) + 1)
} else {
occ.set(r, 1)
}
N = Math.floor(N / 10);
}
for (i of occ) {
if (i[0] != i[1]) {
document.write( "No<br>" );
return ;
}
}
document.write( "Yes<br>" );
}
let N = 3331;
check(N);
</script>
|
Time Complexity: O(D), D = number of digits in N
Auxiliary Space: O(D)