Top 150 InterviewEasy

Top K Frequent Elements

Detailed guide and Python implementation for the 'Top K Frequent Elements' problem.

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?
Consider using Arrays & Hashing-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

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

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.