#2671
Frequency Tracker
MediumHash TableDesignHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(1) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(1)Space O(n)
The optimal solution uses two hash maps: one to track the frequency of each number and another to track how many numbers have a specific frequency. This allows for efficient updates and queries.
⚙️
Algorithm
5 steps- 1Step 1: Use a hash map to store the frequency of each number.
- 2Step 2: Use another hash map to store how many numbers have each frequency.
- 3Step 3: For add, update the frequency of the number and adjust the frequency counts accordingly.
- 4Step 4: For deleteOne, decrease the frequency and adjust the frequency counts.
- 5Step 5: For hasFrequency, simply check if the frequency exists in the frequency map.
solution.py29 lines
1class FrequencyTracker:
2 def __init__(self):
3 self.freq_map = {}
4 self.count_map = {}
5
6 def add(self, number):
7 old_freq = self.freq_map.get(number, 0)
8 new_freq = old_freq + 1
9 self.freq_map[number] = new_freq
10 self.count_map[old_freq] = self.count_map.get(old_freq, 0) - 1
11 if self.count_map[old_freq] == 0:
12 del self.count_map[old_freq]
13 self.count_map[new_freq] = self.count_map.get(new_freq, 0) + 1
14
15 def deleteOne(self, number):
16 old_freq = self.freq_map.get(number, 0)
17 if old_freq > 0:
18 new_freq = old_freq - 1
19 self.freq_map[number] = new_freq
20 self.count_map[old_freq] = self.count_map.get(old_freq, 0) - 1
21 if self.count_map[old_freq] == 0:
22 del self.count_map[old_freq]
23 if new_freq > 0:
24 self.count_map[new_freq] = self.count_map.get(new_freq, 0) + 1
25 else:
26 del self.freq_map[number]
27
28 def hasFrequency(self, frequency):
29 return frequency in self.count_map and self.count_map[frequency] > 0ℹ
Complexity note: The time complexity is O(1) for each operation because we are using hash maps for constant time lookups and updates. The space complexity is O(n) due to storing frequencies and counts.
- 1Using hash maps allows for efficient frequency tracking.
- 2Maintaining a separate count of frequencies helps in quick queries.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.