CodeArchon

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
0
1
1
1
2
2
3
2
4
3
5
Mapcount
empty
1/9
Narrationstep 1 of 9

Goal: top 2 most-visited booths. Phase 1 — tally every visit.

1def top_k(visits: list[int], k: int) -> list[int]:
2 count: dict[int, int] = {}
3 for v in visits:
4 count[v] = count.get(v, 0) + 1
5 pairs = sorted(count.items(), key=lambda p: -p[1])
6 return [v for v, _ in pairs[:k]]
Variables
k=2
phase=tally

How to think about it

  1. Count every booth visit — hash map value → count.
  2. You need the top k by count. Sorting is a straightforward first solution.
  3. Sort entries by count descending; the first k are the answer.
  4. 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