Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

K Most Frequent Elements

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is K Most Frequent Elements. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Inc.'s ranking pipeline receives an integer array of event values. Return the k values that occur most frequently.

Count each distinct value, then select the k highest-frequency values. If two values have the same frequency, return the smaller value first. The final result must therefore be ordered by decreasing frequency, followed by increasing numeric value.

Formal Specification

Implement top_k_frequent(nums, k). The input nums is a list of integers, and k is an integer. Return a list containing exactly k distinct integers, ordered according to the rules above.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= k <= number of distinct values in nums
  • -10^9 <= nums[i] <= 10^9
  • The input contains at least k distinct values

Function Signature

def top_k_frequent(nums, k):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output