Skip to content
Programming101
Programming101

Learn everything about programming

  • Home
  • CS Subjects
    • IoT – Internet of Things
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programming101

Learn everything about programming

HackerRank Frequency Queries problem solution

YASH PAL, 31 July 2024

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.

HackerRank Frequency Queries Interview preparation kit solution

Problem solution in Python programming.

#!/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()

Problem solution in Java Programming.

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 interview prepration kit

Post navigation

Previous post
Next post
  • How AI Is Revolutionizing Personalized Learning in Schools
  • GTA 5 is the Game of the Year for 2024 and 2025
  • Hackerrank Day 5 loops 30 days of code solution
  • Hackerrank Day 6 Lets Review 30 days of code solution
  • Hackerrank Day 14 scope 30 days of code solution
©2025 Programming101 | WordPress Theme by SuperbThemes