[LeetCode] Frequency Tracker

2671. Frequency Tracker

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 the FrequencyTracker object with an empty array initially.
  • void add(int number): Adds number to the data structure.
  • void deleteOne(int number): Deletes one occurence of number from the data structure. The data structure may not contain number, and in this case nothing is deleted.
  • bool hasFrequency(int frequency): Returns true if there is a number in the data structure that occurs frequency number of times, otherwise, it returns false.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

class FrequencyTracker {
unordered_map<int, int> freq;
unordered_map<int, int> rfreq;
public:
FrequencyTracker() {

}

void add(int number) {
rfreq[freq[number]] -= 1;
freq[number] += 1;
rfreq[freq[number]] += 1;
}

void deleteOne(int number) {
if(freq[number] == 0) return;
rfreq[freq[number]] -= 1;
freq[number] -= 1;
rfreq[freq[number]] += 1;
}

bool hasFrequency(int frequency) {
if(frequency == 0) return true;
return rfreq[frequency] > 0;
}
};

/**
* Your FrequencyTracker object will be instantiated and called as such:
* FrequencyTracker* obj = new FrequencyTracker();
* obj->add(number);
* obj->deleteOne(number);
* bool param_3 = obj->hasFrequency(frequency);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/05/07/PS/LeetCode/frequency-tracker/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.