BugForge
DSA

Top K Viewed Products

Mediumhash mapheapbucket sort 00:00

Given the stream of product ids users viewed, return the k most viewed ids, most viewed first. Break ties by smaller id first.

Signature

topK(views: int[], k: int) → int[]
Example 1
views = [1,1,1,2,2,3]
k = 2
output = [1,2]
1 seen 3×, 2 seen 2×
Example 2
views = [4,4,5,5,6]
k = 2
output = [4,5]
4 and 5 tie at 2 views; 6 has 1

Constraints

  • 1 ≤ n ≤ 10^5
  • 1 ≤ k ≤ number of distinct ids
Run checks the examples. Submit runs every hidden test (17, including large inputs that catch slow solutions).