We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
You are iterating the map for finding whether the required frequency is present or not. Try maintaining the frequency to values map. So you won't have to iterate the map. see below code :-
static List freqQuery(List queries) {
List result = new ArrayList<>();
Map operationsMap = new HashMap();
Map<Integer, Set<Integer>> frequencyMap = new HashMap<>();
for (int[] query : queries) {
switch (query[0]) {
case 1:
Integer m = operationsMap.get(query[1]);
if (m == null) {
operationsMap.put(query[1], 1);
Set<Integer> sampleMap = frequencyMap.get(1);
if (sampleMap != null)
sampleMap.add(query[1]);
else
frequencyMap.put(1, new HashSet() {
{
add(query[1]);
}
});
} else {
operationsMap.put(query[1], ++m);
frequencyMap.get(m - 1).remove(query[1]);
Set<Integer> sampleMap = frequencyMap.get(m);
if (sampleMap != null)
sampleMap.add(query[1]);
else
frequencyMap.put(m, new HashSet() {
{
add(query[1]);
}
});
}
break;
case 2:
Integer n = operationsMap.get(query[1]);
if (n == null)
break;
else if (n == 1) {
operationsMap.remove(query[1]);
frequencyMap.get(1).remove(query[1]);
} else {
operationsMap.put(query[1], --n);
frequencyMap.get(n + 1).remove(query[1]);
Set<Integer> sampleMap = frequencyMap.get(n);
if (sampleMap != null)
sampleMap.add(query[1]);
else
frequencyMap.put(n, new HashSet() {
{
add(query[1]);
}
});
}
break;
case 3:
result.add((frequencyMap.get(query[1]) == null || frequencyMap.get(query[1]).isEmpty()) ? 0 : 1);
break;
}
}
return result;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Frequency Queries
You are viewing a single comment's thread. Return to all comments →
You are iterating the map for finding whether the required frequency is present or not. Try maintaining the frequency to values map. So you won't have to iterate the map. see below code :-
return result; }