Problem
Design a data structure that keeps track of the values in it and answers some queries regarding their frequencies.
Implement the FrequencyTracker
class.
FrequencyTracker()
: Initializes theFrequencyTracker
object with an empty array initially.void add(int number)
: Addsnumber
to the data structure.void deleteOne(int number)
: Deletes one occurrence ofnumber
from the data structure. The data structure may not containnumber
, and in this case nothing is deleted.bool hasFrequency(int frequency)
: Returnstrue
if there is a number in the data structure that occursfrequency
number of times, otherwise, it returnsfalse
.
Example 1:
Input
["FrequencyTracker", "add", "add", "hasFrequency"]
[[], [3], [3], [2]]
Output
[null, null, null, true]
Explanation
FrequencyTracker frequencyTracker = new FrequencyTracker();
frequencyTracker.add(3); // The data structure now contains [3]
frequencyTracker.add(3); // The data structure now contains [3, 3]
frequencyTracker.hasFrequency(2); // Returns true, because 3 occurs twice
Example 2:
Input
["FrequencyTracker", "add", "deleteOne", "hasFrequency"]
[[], [1], [1], [1]]
Output
[null, null, null, false]
Explanation
FrequencyTracker frequencyTracker = new FrequencyTracker();
frequencyTracker.add(1); // The data structure now contains [1]
frequencyTracker.deleteOne(1); // The data structure becomes empty []
frequencyTracker.hasFrequency(1); // Returns false, because the data structure is empty
Example 3:
Input
["FrequencyTracker", "hasFrequency", "add", "hasFrequency"]
[[], [2], [3], [1]]
Output
[null, false, null, true]
Explanation
FrequencyTracker frequencyTracker = new FrequencyTracker();
frequencyTracker.hasFrequency(2); // Returns false, because the data structure is empty
frequencyTracker.add(3); // The data structure now contains [3]
frequencyTracker.hasFrequency(1); // Returns true, because 3 occurs once
Constraints:
1 <= number <= 105
1 <= frequency <= 105
- At most,
2 * 105
calls will be made toadd
,deleteOne
, andhasFrequency
in total.
Solution (Java)
class FrequencyTracker {
int[] b;
HashMap<Integer,Integer> map;
public FrequencyTracker() {
b= new int[200001];
map = new HashMap<>();
}
public void add(int number) {
int x = map.getOrDefault(number,0);
if(x!=0){
b[x]--;
}
b[x+1]++;
map.put(number,x+1);
}
public void deleteOne(int number) {
int x =map.getOrDefault(number,0);
if(x==0){ // don't do anything
}
else {
b[x]--;
b[x-1]++;
map.put(number,x-1);
}
}
public boolean hasFrequency(int frequency) {
return b[frequency]>0;
}
}
/**
* Your FrequencyTracker object will be instantiated and called as such:
* FrequencyTracker obj = new FrequencyTracker();
* obj.add(number);
* obj.deleteOne(number);
* boolean param_3 = obj.hasFrequency(frequency);
*/
Explain:
nope.
Complexity:
- Time complexity : O(n).
- Space complexity : O(n).