Back to Practice Dashboard
Top 150 InterviewEasy

Top K Frequent Elements

Learn how to solve the 'Top K Frequent Elements' problem. This detailed resource details brute force and optimized approaches.

Problem Statement

Easy

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

Write a function topKFrequent(nums: List[int], k: int) -> List[int].

Constraints
  • 1 <= len(nums) <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • k is in the range [1, number of unique elements in nums]
  • The answer is guaranteed to be unique

Examples

Example 1
Input
nums = [1, 1, 1, 2, 2, 3], k = 2
Output
[1, 2]
Explanation

1 appears 3 times and 2 appears 2 times. These are the 2 most frequent elements.

Example 2
Input
nums = [1], k = 1
Output
[1]
Explanation

There is only one element, so it is the most frequent.

Need a Hint?
Analyze the input constraints. Try sorting first (O(n log n)) or using a hash map/set to track seen elements in O(n) time.
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor