Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Top K Frequent Elements

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

Your question is Top K 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

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):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output