EasyNo. 2190
Most Frequent Number Following Key In an Array — LeetCode 2190 Python Solution
- Pattern
- Hash Map
- Topics
- Array, Hash Table, Counting
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given a 0-indexed integer array nums. You are also given an integer key, which is present in nums.
Example
- Input
- nums = [1,100,200,1,100], key = 1
- Output
- 100
- Explanation
- For target = 100, there are 2 occurrences at indices 1 and 4 which follow an occurrence of key.
Python solution
class Solution:
def mostFrequent(self, nums: List[int], key: int) -> int:
cnt = Counter()
ans = mx = 0
for a, b in pairwise(nums):
if a == key:
cnt[b] += 1
if mx < cnt[b]:
mx = cnt[b]
ans = b
return ansComplexity
- Time
- O(n)
- Space · auxiliary
- O(M)
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2190. Most Frequent Number Following Key In an Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0169 | Majority Element | Easy |
| 0229 | Majority Element II | Medium |
| 0347 | Top K Frequent Elements | Medium |
| 0594 | Longest Harmonious Subsequence | Easy |
| 0621 | Task Scheduler | Medium |
| 0692 | Top K Frequent Words | Medium |
Frequently asked questions
- How hard is LeetCode 2190. Most Frequent Number Following Key In an Array?
LeetCode 2190. Most Frequent Number Following Key In an Array is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2190. Most Frequent Number Following Key In an Array?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2190. Most Frequent Number Following Key In an Array?
The Python solution on this page uses O(M) auxiliary space.
- What topics does LeetCode 2190. Most Frequent Number Following Key In an Array cover?
LeetCode 2190. Most Frequent Number Following Key In an Array is tagged Array, Hash Table and Counting on LeetCode.