Top K Frequent Elements
Updated
Problem statement
Given an integer array nums and an integer k, return the k distinct values that occur most frequently.
For this exercise, order values by decreasing frequency. If two values have equal frequency, put the value whose first occurrence appears earlier in nums first. Return exactly k values in that order.
After solving, compare a size-k heap with a frequency-bucket approach. Explain how their time and space costs differ.
Function
topKFrequentElements(nums: int[], k: int) → int[]Examples
Example 1
nums = [1,1,1,2,2,3]k = 2return = [1,2]Value 1 appears three times and value 2 appears twice.
Example 2
nums = [4,5,4,5,6]k = 2return = [4,5]Values 4 and 5 tie at two occurrences; 4 appeared first.
Example 3
nums = [-3,-3,7,7,7,-3,9]k = 2return = [-3,7]Values -3 and 7 each appear three times. The first -3 precedes the first 7.
Constraints
1 <= nums.length <= 100000.- Each value is a signed 32-bit integer.
1 <= k <=the number of distinct values innums.
More Microsoft Phone Screen questions
- Config Store with Priority OverridesPHONE SCREEN · Seen Nov 2026
- Corporation Reporting LinesPHONE SCREEN · Seen Oct 2026
- Random Forest Classifier from ScratchPHONE SCREEN · Seen Oct 2026
- Least Recently Used CacheOA · PHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
- Greedy and Beam Sentence DecodingPHONE SCREEN · ONSITE INTERVIEW · Seen Sep 2026
- 3SumPHONE SCREEN · ONSITE INTERVIEW · Seen Sep 2026
- Arithmetic Expression EvaluatorPHONE SCREEN · Seen Sep 2026
- Employee Hierarchy Cycle and Depth AnalysisPHONE SCREEN · Seen Sep 2026
- Most Visited String SectorsPHONE SCREEN · Seen Sep 2026
- Infer a Lexicographically Smallest Alien AlphabetPHONE SCREEN · ONSITE INTERVIEW · Seen Aug 2026
Similar questions at other companies
- Merge Event PreferencesAirbnb · PHONE SCREEN · ONSITE INTERVIEWAirbnb interview questions
- Top K Frequent ElementsAmazon · OA · PHONE SCREEN · ONSITE INTERVIEW
- Financial Account LedgerStripe · OA · PHONE SCREENStripe interview questions
- Paged KV Cache AccessNVIDIA · PHONE SCREENNVIDIA interview questions
- Mutual-Friend RecommendationsMeta · PHONE SCREEN · ONSITE INTERVIEWMeta interview questions
- Balanced Session ManagerPalantir · PHONE SCREENPalantir interview questions
- Integers With Multiple Sum of Two CubesCharta Health · PHONE SCREEN · ONSITE INTERVIEWCharta Health interview questions
- Match Orders by Price and Arrival TimeAkuna Capital · OA · PHONE SCREEN · ONSITE INTERVIEWAkuna Capital interview questions
- Worst-Performing Ads by CTR in a Campaign TreeUber · PHONE SCREENUber interview questions
- In-Memory Priority Task SchedulerRippling · PHONE SCREENRippling interview questions