Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
Top K Frequent Elements
00:00
5 left

Top K Frequent Elements

EasyPython

Problem

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

Formal Specification

  • Input:
    • nums, a list of integers
    • k, an integer
  • Output:
    • A list containing the k most frequent elements in nums

If multiple valid answers exist, return any one of them.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= k <= number of unique elements in nums
  • -10^4 <= nums[i] <= 10^4
  • The answer may be returned in any order

Function Signature

def top_k_frequent(nums, k):
Interviewer

Your question is Top K Frequent Elements. Start with the requirements in the Question tab.

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.
CodePython 3
You need to log in / sign up to run or submit.Ln 2
Run your code to see test output here.