#2190
Most Frequent Number Following Key In an Array
EasyArrayHash TableCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can achieve better performance by using a single pass through the array and a hash map to count occurrences, which reduces the time complexity significantly.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a hash map to count occurrences of each number following the key.
- 2Step 2: Loop through the array only once, checking for the key and updating counts for the next number.
- 3Step 3: After the loop, find the number with the maximum count in the hash map.
solution.py9 lines
1# Full working Python code
2
3def most_frequent(nums, key):
4 count_map = {}
5 for i in range(len(nums) - 1):
6 if nums[i] == key:
7 next_num = nums[i + 1]
8 count_map[next_num] = count_map.get(next_num, 0) + 1
9 return max(count_map, key=count_map.get)ℹ
Complexity note: The complexity is O(n) because we traverse the array only once and use a hash map to store counts, which is efficient for lookups and insertions.
- 1Using a hash map allows for efficient counting of occurrences.
- 2A single pass through the array is sufficient to gather all necessary data.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.