#3092
Most Frequent IDs
MediumArrayHash TableHeap (Priority Queue)Ordered SetHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
This approach uses a hash map to efficiently track the frequencies of IDs and a max-heap to quickly retrieve the most frequent ID. This reduces the need to repeatedly scan the entire collection.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a frequency map to track occurrences of each ID.
- 2Step 2: Use a max-heap to keep track of the most frequent IDs.
- 3Step 3: For each step i, update the frequency map based on freq[i].
- 4Step 4: Update the max-heap and retrieve the maximum frequency efficiently.
- 5Step 5: Append the maximum frequency to ans.
solution.py15 lines
1import heapq
2from collections import defaultdict
3
4def most_frequent_ids(nums, freq):
5 ans = []
6 collection = defaultdict(int)
7 max_heap = []
8 for i in range(len(nums)):
9 collection[nums[i]] += freq[i]
10 if freq[i] > 0:
11 heapq.heappush(max_heap, (-collection[nums[i]], nums[i]))
12 while max_heap and -max_heap[0][0] != collection[max_heap[0][1]]:
13 heapq.heappop(max_heap)
14 ans.append(-max_heap[0][0] if max_heap else 0)
15 return ansℹ
Complexity note: The time complexity is O(n log n) due to the use of a max-heap to maintain the most frequent IDs, where n is the number of steps. Each insertion and removal operation in the heap takes log n time.
- 1Using a hash map allows for efficient frequency counting.
- 2A max-heap helps in quickly retrieving the most frequent ID.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.