Skip to content
Programmingoneonone
Programmingoneonone
  • Engineering Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
    • 100+ C++ Programs
  • Solutions
    • HackerRank
      • Algorithms Solutions
      • C solutions
      • C++ solutions
      • Java solutions
      • Python solutions
    • Leetcode Solutions
    • HackerEarth Solutions
  • Work with US
Programmingoneonone
Programmingoneonone

HackerRank Frequency Queries problem solution

YASH PAL, 31 July 20247 February 2026

In this HackerRank Frequency queries Interview preparation kit problem solution, complete the freqQuery function in the editor below. It must return an array of integers where each element is a 1 if there is at least one element value with the queried number of occurrences in the current array, or 0 if there is not.

Function Description

Complete the freqQuery function in the editor below.

freqQuery has the following parameter(s):

  • int queries[q][2]: a 2-d array of integers

Returns
– int[]: the results of queries of type 3.

HackerRank Frequency Queries Interview preparation kit solution

HackerRank Frequency Queries problem solution in Python.

#!/bin/python3

import math
import os
import random
import re
import sys
from collections import defaultdict

# Complete the freqQuery function below.
def freqQuery(queries):
    res = []
    fre = defaultdict(int)
    for x in queries:
        if x[0] == 1:
            fre[x[1]] += 1
        elif x[0] == 2:
            if x[1] in fre and fre[x[1]] > 0:
                fre[x[1]] -= 1
        else:
            res.append(1 if x[1] in set(fre.values()) else 0)
    return res

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    q = int(input().strip())

    queries = []

    for _ in range(q):
        queries.append(list(map(int, input().rstrip().split())))

    ans = freqQuery(queries)

    fptr.write('n'.join(map(str, ans)))
    fptr.write('n')

    fptr.close()

Frequency Queries problem solution in Java.

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

public class Solution {

    // Complete the freqQuery function below.
    static List<Integer> freqQuery (BufferedReader bufferedReader, int q)throws IOException {

        HashMap<Integer, Integer> valuesToCounts = new HashMap<>();
        HashMap<Integer, Set<Integer>> countsToValues = new HashMap<>();
        ArrayList<Integer> results = new ArrayList<>(); 
        int size = q;
           
        for (int i = 0; i < q; i++) {
            String[] query = bufferedReader.readLine().split(" ");
            int operation = Integer.parseInt(query[0]);
            int number = Integer.parseInt(query[1]);

            int oldCount = valuesToCounts.getOrDefault(number, 0); 
            int newCount; 

            if (operation == 1) {
                newCount = oldCount + 1; 
                valuesToCounts.put(number, newCount);
                
                if (countsToValues.containsKey(oldCount)) {
                    countsToValues.get(oldCount).remove(number);
                }
                countsToValues.putIfAbsent(newCount, new HashSet<>());
                countsToValues.get(newCount).add(number);
            }

            if (operation == 2) {
                newCount = (oldCount > 1) ? oldCount - 1 : 0;
                valuesToCounts.put(number, newCount);

                if (countsToValues.containsKey(oldCount)) {
                    countsToValues.get(oldCount).remove(number);
                }

                countsToValues.putIfAbsent(newCount, new HashSet<>());
                countsToValues.get(newCount).add(number);
            }

            if (operation == 3) {
                if (number > size) results.add(0);
                else {
                    results.add((number == 0 || countsToValues.getOrDefault(number, Collections.emptySet()).size() > 0) ? 1 : 0);
                }
            }
        }

        return results; 
    }

    public static void main(String[] args) throws IOException {
        try (BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(System.in))) {
            
            int q = Integer.parseInt(bufferedReader.readLine().trim());

            List<Integer> ans = freqQuery(bufferedReader, q); 
          
            try (BufferedWriter bufferedWriter = new BufferedWriter(
                        new FileWriter(System.getenv("OUTPUT_PATH")))) {
            
                bufferedWriter.write(ans.stream().map(Object::toString)
                            .collect(joining("n")) + "n");
            }
        }
    }
}

Problem solution in C++ programming.

#include<bits/stdc++.h>
using namespace std;

//m1 is to store values with their frequency
//m2 is to store the count of every frequency
map<int,int> m1,m2;

int main()
{
    int q;
    scanf("%d",&q);
    int a[q],b[q];
    
    // array of type of queries
    for(int i=0;i<q;i++)
        scanf("%d",&a[i]);
    
    // array of values
    for(int i=0;i<q;i++)
        scanf("%d",&b[i]);
    
    for(int i=0;i<q;i++)
    {
        // insert query
        if(a[i]==1)
        {
            int k=m1[b[i]];
            //decrease count of present frequency
            if(k>0)
                m2[k]--;
            //increase occurence of a number
            m1[b[i]]++;
            //increase count of present frequency + 1
            m2[k+1]++;
        }
        
        //delete query
        else if(a[i]==2)
        {
            int k=m1[b[i]];
            if(k>0)
            {
                //decrease occurence of a number
                m1[b[i]]--;
                //decrease count of present frequency
                m2[k]--;
                //increase count of present frequency - 1
                if(k-1>0) 
                    m2[k-1]++;
            }
        }
        else
        {
            //true if the count of asked frequency is non-zero
            if(m2[b[i]]>0)
                printf("1n");
            else
                printf("0n");
        }
    }
    return 0;
}

Problem solution in python3 programming.

#!/bin/python3


import os
from collections import defaultdict


def freqQuery(queries):
    elementFreq = defaultdict(int)
    freqCount = defaultdict(int)
    ans = []
    for i, j in queries:
        if i == 1:
            if freqCount[elementFreq[j]]:
                freqCount[elementFreq[j]] -= 1
            elementFreq[j] += 1
            freqCount[elementFreq[j]] += 1            
        elif i == 2:
            if elementFreq[j]:
                freqCount[elementFreq[j]] -= 1
                elementFreq[j] -= 1
                freqCount[elementFreq[j]] += 1
        else:
            # operation 3
            if j in freqCount and freqCount[j]:
                ans.append(1)
            else:
                ans.append(0)
    return ans



if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    q = int(input())

    queries = []

    for _ in range(q):
        queries.append(map(int, input().rstrip().split()))

    ans = freqQuery(queries)

    fptr.write('n'.join(map(str, ans)))
    fptr.write('n')

    fptr.close()

coding problems solutions Hackerrank Problems Solutions interview prepration kit HackerRank

Post navigation

Previous post
Next post

Programmingoneonone

We at Programmingoneonone, also known as Programming101 is a learning hub of programming and other related stuff. We provide free learning tutorials/articles related to programming and other technical stuff to people who are eager to learn about it.

Pages

  • About US
  • Contact US
  • Privacy Policy

Practice

  • Java
  • C++
  • C

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes