Z14

Top K Frequent Elements

Mid / Senior Engineer
Target Time: 25 - 35 Minutes
Type: ARRAY

Problem Statement & Objective

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

Function Signature (Python)

top_k_frequent(nums: list[int], k: int) -> list[int]

Input & Output Contract

Output Rule:List of k most frequent elements.

System Constraints

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

Example Execution Walkthrough

nums = [1,1,1,2,2,3], k = 2
result: [1, 2]

Example Test Scenarios (3)

Example 1
Input:[[1,1,1,2,2,3],2]
Expected Output:[1,2]
Example 2: Single Element
Input:[[1],1]
Expected Output:[1]
Example 3: Eşit Frekans
Input:[[4,4,5,5,6],2]
Expected Output:[4,5]
Loading Python Editor...
Input Parameters
[
  [
    1,
    1,
    1,
    2,
    2,
    3
  ],
  2
]
Expected Output
[
  1,
  2
]