Top K Frequent Elements
Updated
Problem statement
Given an integer array nums and k, return its k most frequent distinct values.
Order the returned values by decreasing frequency. When two values occur equally often, put the value whose first occurrence is earlier in nums first. Apply this same rule when a tie crosses the cutoff.
Return each selected value exactly once. A zero k returns an empty array. The input guarantees k does not exceed the number of distinct values. Implement the frequency-bucket optimization as well as a comparison-sort approach.
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 and value 2 twice.
Example 2
nums = [9,4,9,4,2]k = 2return = [9,4]The tied values 9 and 4 occur twice; 9 appeared first.
Example 3
nums = []k = 0return = []An empty array permits only k=0.
Constraints
0 <= nums.length <= 100000.-1000000000 <= nums[i] <= 1000000000.0 <= k <= number of distinct values in nums.- Array positions are zero-based. Equal-frequency values are ordered by their first positions, not their numeric values.
More Headlands Technologies Phone Screen questions
- Integer Compression OffsetPHONE SCREEN · Seen Oct 2026
- Market Order BookPHONE SCREEN · Seen Jun 2026
- Gradient Descent on a Sinusoidal ObjectivePHONE SCREEN · Seen Apr 2026
- Pearson Correlation CoefficientPHONE SCREEN · Seen Apr 2026
- Queue Mean from Corrective SnapshotsPHONE SCREEN · Seen Mar 2026
- Queue Mean QueriesPHONE SCREEN · Seen Mar 2026
- CPU Register Bitwise OperationsPHONE SCREEN · Seen Nov 2025
- Merge K Sorted SequencesPHONE SCREEN · Seen Oct 2024
- Top Trade Events by NotionalPHONE SCREEN · Seen May 2024
- Fixed-Size Memory PoolPHONE SCREEN · Seen May 2024
Similar questions at other companies
- Top K Frequent ElementsAmazon · OA · PHONE SCREEN · ONSITE INTERVIEW
- Mutual-Friend RecommendationsMeta · PHONE SCREEN · ONSITE INTERVIEWMeta interview questions
- 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