Top K Frequent Elements
Updated
Problem statement
Given a non-empty integer array nums and an integer k, return the k values that occur most frequently.
Order the result by decreasing frequency. When two values have the same frequency, the value whose first occurrence in nums appears earlier comes first.
Design an approach that improves on sorting all n input elements in O(n log n) time, and be prepared to discuss the space trade-offs.
Function
topKFrequent(nums: int[], k: int) → int[]Examples
Example 1
nums = [1,1,1,2,2,3]k = 2return = [1,2]1 occurs three times and 2 occurs twice, so they are the two most frequent values.
Example 2
nums = [4,6,4,6,5]k = 2return = [4,6]4 and 6 both occur twice. The first 4 appears before the first 6, so 4 wins the tie.
Example 3
nums = [-1,-1,2,3,2,3]k = 3return = [-1,2,3]All three values occur twice, so their first-occurrence positions determine the complete result order.
Constraints
1 <= nums.length <= 100000.-1000000000 <= nums[i] <= 1000000000.1 <= k <=the number of distinct values innums.- Return exactly
kdistinct values in the required order.
More Google Phone Screen questions
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Periodic-Color Binary Forest RootsPHONE SCREEN · Seen Nov 2026
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Best Stock Trade with Buy and Sell DaysPHONE SCREEN · Seen Nov 2026
- Word Chain Jumps in a GridPHONE SCREEN · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Apartment Housemate PreferencesPHONE SCREEN · Seen Nov 2026
- Price at Query TimestampsPHONE SCREEN · Seen Nov 2026
- Course Schedule Cycle DetectionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Top K Frequent ElementsAmazon · OA · PHONE SCREEN · ONSITE INTERVIEW
- Mutual-Friend RecommendationsMeta · PHONE SCREEN · ONSITE INTERVIEWMeta interview questions
- Top K Frequent ElementsApple · PHONE SCREENApple interview questions
- Top K Frequent ElementsC3.ai · PHONE SCREENC3.ai interview questions
- Smallest Range Covering Elements from K ListsSnap Inc. · PHONE SCREENSnap Inc. interview questions
- Top K Frequent ElementsCapgemini · ONSITE INTERVIEWCapgemini 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