Top K Most Frequent Values
Updated
Problem statement
You are given an integer array nums and an integer k. Rank the distinct values of nums by how many times each one appears:
- a value that appears more times ranks higher;
- if two values appear the same number of times, the smaller value ranks higher.
Return the k highest-ranked values, in rank order (the highest first).
Function
kMostFrequent(nums: int[], k: int) → int[]Examples
Example 1
nums = [4,1,4,6,1,4,9,6,6,6]k = 2return = [6,4]Count each value: 6 appears 4 times, 4 appears 3 times, 1 appears 2 times and 9 appears once. So the ranking is 6, 4, 1, 9, and the first k = 2 values are [6, 4].
Example 2
nums = [5,-2,5,3,-2,3,8]k = 2return = [-2,3]5, -2 and 3 each appear 2 times, and 8 appears once. The three tied values are ranked by value, smallest first: -2, 3, 5. So the ranking is -2, 3, 5, 8, and the answer for k = 2 is [-2, 3].
5 is left out even though it appears first in nums: the order in the array does not matter, only the counts and the values.
Example 3
nums = [2,9,2,9,9,0]k = 3return = [9,2,0]9 appears 3 times, 2 appears 2 times and 0 appears once. Here k = 3 equals the number of distinct values, so the answer is the whole ranking, [9, 2, 0]. It is in rank order, not sorted by value.
Constraints
1 <= nums.length <= 10^4-10^4 <= nums[i] <= 10^41 <= k <=the number of distinct values innums
More Nutanix Phone Screen questions
- Swap Adjacent Linked List NodesPHONE SCREEN · Seen Mar 2025
- Unique Triplets Summing to ZeroPHONE SCREEN · Seen Sep 2024
- Find the Duplicate in a Read-Only ArrayPHONE SCREEN · Seen Apr 2021
- Kth Largest Element in an ArrayPHONE SCREEN · Seen Feb 2020
- Kth Smallest Element in a BSTPHONE SCREEN · Seen Feb 2020
- Outline of a Binary TreePHONE SCREEN · Seen Jan 2020
- Print All File and Folder PathsPHONE SCREEN · Seen Dec 2019
- Inorder Predecessor in a BSTPHONE SCREEN · Seen Jan 2019
- K Largest and K Smallest ValuesPHONE SCREEN · Seen Jan 2019
- Odd Numbers Up and BackPHONE SCREEN · Seen Jan 2019
Similar questions at other companies
- Filter, Sort, and Deduplicate Scheduled TasksRippling · PHONE SCREEN · ONSITE INTERVIEWRippling interview questions
- Longest Consecutive SequenceJP Morgan Chase · PHONE SCREENJP Morgan Chase interview questions
- Top K Frequent Elements with a Recency TiebreakSwiggy · PHONE SCREEN
- Pins Violation Log QueriesPinterest · PHONE SCREENPinterest interview questions
- Group AnagramsWorkday · PHONE SCREEN
- Build a Task and Subtask HierarchyStripe · PHONE SCREENStripe interview questions
- Find All Points Within a RadiusGoogle · PHONE SCREENGoogle interview questions
- Resource Reconciler: Plan and Apply CreatesPerplexity AI · PHONE SCREENPerplexity AI interview questions
- Top K Frequent ElementsAmazon · OA · PHONE SCREEN
- Build a Pivot Table with TotalsSigma Computing · PHONE SCREEN