mediumArrays & HashingAmazonMetaApple
Festival Booth Favorites
Each entry in the festival log is a booth number a guest visited. Report the k most-visited booths.
Given an integer array `visits` and an integer `k`, return the `k` most frequent elements. You may return the answer in any order.
Choose approach
1
01
11
22
32
43
5Mapcount
empty
1/9
Narrationstep 1 of 9
Goal: top 2 most-visited booths. Phase 1 — tally every visit.
Variables
k=2
phase=tally
How to think about it
- Count every booth visit — hash map value → count.
- You need the top k by count. Sorting is a straightforward first solution.
- Sort entries by count descending; the first k are the answer.
- O(n log n) overall; O(n) is possible via bucket sort or a size-k heap.
Edge cases to catch in interview
- k = 1 — just the single max.
- All elements unique — every element has count 1; any k are valid.
- k equals the number of distinct booths — return all of them.
Examples
Example 1
[1, 2]{"visits":[1,1,1,2,2,3],"k":2,"values":[1,1,1,2,2,3]}
1 appears 3x, 2 appears 2x.
Example 2
[1]{"visits":[1],"k":1,"values":[1]}
Only one booth.
Example 3
[1, 2]{"visits":[1,2,1,2,1,2,3,1,3,2],"k":2,"values":[1,2,1,2,1,2,3,1,3,2]}
1 → 4, 2 → 4, 3 → 2.
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed