Top K Frequent Elements
Updated
Problem statement
Given an integer array nums and an integer k, return the k distinct values that occur most often.
Return them in decreasing frequency. When two values have the same frequency, put the smaller value first. Apply that same rule when a tie crosses the k-th position.
Function
topKFrequent(nums: int[], k: int) → int[]Examples
Example 1
nums = [1,1,1,2,2,3]k = 2return = [1,2]Value 1 occurs three times, 2 occurs twice, and 3 occurs once. The two most frequent values are [1,2].
Example 2
nums = [4,4,-1,-1,2]k = 1return = [-1]Values -1 and 4 both occur twice. The smaller value, -1, wins the tie for the only returned position.
Constraints
- 1 <= nums.length <= 10^5.
- Every value in nums is between -10^4 and 10^4, inclusive.
- 1 <= k.
- k is at most the number of distinct values in nums.
More Apple Phone Screen questions
- Subarray Product Less Than KPHONE SCREEN · Seen Nov 2026
- Evaluate DivisionPHONE SCREEN · Seen Nov 2026
- Reverse a Linked ListPHONE SCREEN · Seen Nov 2026
- Validate a BST with a Custom ComparisonPHONE SCREEN · Seen Nov 2026
- Design a Food Rating SystemPHONE SCREEN · Seen Oct 2026
- Days Until Poisoned Plants StabilizePHONE SCREEN · Seen Oct 2026
- Capture Surrounded Regions with Union-FindPHONE SCREEN · Seen Oct 2026
- Maintain a Consistent-Hashing RingPHONE SCREEN · Seen Oct 2026
- Count Nodes in a ChainPHONE SCREEN · Seen Oct 2026
- Run-Length DecodingPHONE SCREEN · Seen Oct 2026
Similar questions at other companies
- Top K Frequent ElementsAmazon · OA · PHONE SCREEN
- Top K Frequent ElementsGoogle · PHONE SCREENGoogle 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
- 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
Apple interview experiences
- Apple SWE Phone Screen: Subarray Products: 1 Experience
- Apple New Grad SWE Java, Coding and Manager Rounds: 1 Experience
- Apple AI Coding and Related Interviews: 17 Experiences
- Apple India SWE New Grad Interviews: 5 Experiences
- Apple New Grad SWE Phone Screens: 12 Experiences (Part 3 of 3)
- Apple New Grad SWE and Embedded: 16 Experiences (Part 2 of 3)