FrontendInterviews.dev

Loading problem…

89. Top K Frequent Elements - Trending Items

Medium•
Acceptance: 100.00%
•
🔓3/3 Pro unlocks today

You're building an analytics dashboard that shows trending products, most viewed pages, or popular content. You need to find the top K most frequently occurring items from a dataset.

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

Requirements

1. Basic Functionality

  • Count frequency of each element
  • Find top K most frequent elements
  • Return in any order
  • Handle cases where k equals array length

Example Usage

topKFrequent([1,1,1,2,2,3], 2); // [1, 2] - 1 appears 3 times, 2 appears 2 times
topKFrequent([1], 1);           // [1]
topKFrequent([4,1,-1,2,-1,2,3], 2); // [-1, 2] - both appear twice

Real-World Context

This problem models real analytics features:

  • Trending products: Show top K most viewed products
  • Popular pages: Display most visited pages
  • Content recommendations: Find most liked/shared content
  • Analytics dashboard: Show top performing metrics

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • k is in the range [1, number of unique elements]
  • It is guaranteed that the answer is unique