Top K Frequent Elements
Updated
Problem statement
You are given an integer array nums and an integer k. Return the k distinct values that appear most often in nums.
Return them in this order:
- A value with a higher count comes before a value with a lower count.
- When two values have the same count, the smaller value comes first.
The same order decides ties for the last spot: if several values share the count of the k-th value, the smaller ones are kept.
Function
topKFrequent(nums: int[], k: int) → int[]Examples
Example 1
nums = [4,4,1,1,1,7,7,4,2]k = 2return = [1,4]The counts are: 1 and 4 appear 3 times, 7 appears 2 times, and 2 appears once. The two most frequent values are 1 and 4. They have the same count, so the smaller value 1 comes first.
Example 2
nums = [5,-2,5,-2,9,9,9]k = 3return = [9,-2,5]9 appears 3 times, and 5 and -2 appear 2 times each. 9 comes first, then -2 before 5 because it is smaller.
Example 3
nums = [3,1,2,3]k = 2return = [3,1]3 appears twice, so it is first. 1 and 2 both appear once and tie for the last spot. The smaller value 1 wins, so the answer is [3, 1].
Constraints
1 <= nums.length <= 5000-10^4 <= nums[i] <= 10^41 <= k <=the number of distinct values innums
More C3.ai interview questions
- Fewest Turns to Open a Wheel LockPHONE SCREEN · Seen Nov 2024
- Days Until a Warmer DayPHONE SCREEN · ONSITE INTERVIEW · Seen Apr 2022
- Longest Run of Ones After Flipping k ZerosPHONE SCREEN · Seen Mar 2022
- Item Prices From Material CostsPHONE SCREEN · Seen Dec 2020
- Adjacent-Key Lock PatternsPHONE SCREEN · Seen Feb 2014
- Drop Recent Duplicate MessagesOA · Seen Oct 2026
- Maximum K-Star SumOA · Seen Oct 2026
- Every Result of Grouping an ExpressionONSITE INTERVIEW · Seen Jan 2023
- Fewest Jumps to the Last IndexONSITE INTERVIEW · Seen Jan 2023
- Rotate a Square Grid ClockwiseONSITE INTERVIEW · Seen Jan 2023
Similar questions at other companies
- Top K Frequent ElementsAmazon · OA · PHONE SCREEN
- Top K Frequent ElementsGoogle · PHONE SCREENGoogle interview questions
- Top K Frequent ElementsApple · PHONE SCREENApple interview questions
- Smallest Range Covering Elements from K ListsSnap Inc. · PHONE SCREENSnap Inc. interview questions
- Top K Frequent ElementsCapgemini · ONSITE INTERVIEWCapgemini interview questions
- Mutual-Friend RecommendationsMeta · ONSITE INTERVIEWMeta interview questions
- Top K Frequent Elements with Larger-Value Tie BreakOracle · ONSITE INTERVIEWOracle interview questions
- Top K Frequent ElementsInfosys · ONSITE INTERVIEWInfosys interview questions
- Rearrange Songs by AuthorZomato / Eternal · OAZomato / Eternal interview questions
- Top K Frequent ElementsBloomberg LP · ONSITE INTERVIEWBloomberg LP interview questions