Frequency Tracker - 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 the FrequencyTracker object with an empty array initially.
  • void add(int number): Adds number to the data structure.
  • void deleteOne(int number): Deletes one occurrence 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.

Input & Output

Example 1 — Basic Operations
$ Input: operations = ["FrequencyTracker", "add", "add", "hasFrequency"], values = [0, 3, 3, 2]
Output: [null, null, null, true]
💡 Note: Create tracker, add 3 twice (frequency 2), hasFrequency(2) returns true since 3 appears 2 times
Example 2 — Delete Operations
$ Input: operations = ["FrequencyTracker", "add", "deleteOne", "hasFrequency"], values = [0, 1, 1, 1]
Output: [null, null, null, false]
💡 Note: Add 1, delete 1, now no numbers exist so hasFrequency(1) returns false
Example 3 — Multiple Numbers
$ Input: operations = ["FrequencyTracker", "add", "add", "add", "hasFrequency", "hasFrequency"], values = [0, 1, 1, 2, 2, 1]
Output: [null, null, null, null, true, true]
💡 Note: Add 1,1,2. Number 1 has frequency 2, number 2 has frequency 1. Both queries return true

Constraints

  • 1 ≤ number ≤ 105
  • 1 ≤ frequency ≤ 105
  • At most 2 × 105 calls to add, deleteOne, and hasFrequency

Visualization

Tap to expand
Frequency Tracker - Dual Hash Maps INPUT Operations: FrequencyTracker add add hasFrequency Values: 0 3 3 2 Data Structures: numToFreq num --> freq {3: 2} freqToCount freq --> count {2: 1} ALGORITHM STEPS 1 Constructor Init two empty hash maps 2 add(3) - First time numToFreq[3] = 1 freqToCount[1]++ {3: 1} {1: 1} 3 add(3) - Second time freqToCount[1]-- (old) numToFreq[3] = 2, freq[2]++ {3: 2} {2: 1} 4 hasFrequency(2) Check freqToCount[2] > 0 freqToCount[2] = 1 --> true FINAL RESULT Final State: numToFreq 3 --> 2 freqToCount 2 --> 1 Output Array: [null, null, null, true] hasFrequency(2) = true Frequency 2 exists (num 3) O(1) per operation Key Insight: Using TWO hash maps enables O(1) time for all operations: 1) numToFreq: tracks frequency of each number | 2) freqToCount: tracks how many numbers have each frequency When adding/deleting, update both maps. For hasFrequency, simply check if freqToCount[freq] > 0. TutorialsPoint - Frequency Tracker | Optimized - Dual Hash Maps Approach
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
28.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen