Top K Frequent Elements with a Recency Tiebreak
Updated
Problem statement
You are given an integer array nums and an integer k. Return the k values that appear most often in nums.
Rank the distinct values of nums with these rules:
- A value that appears more times ranks higher.
- If two values appear the same number of times, the one whose last appearance in
numsis at a higher index ranks higher.
Two different values never share a last index, so this ranking has no ties.
Return the k highest-ranked values in rank order, starting with the highest.
Function
topKFrequent(nums: int[], k: int) → int[]Examples
Example 1
nums = [4,1,4,2,1,3]k = 2return = [1,4]4 and 1 each appear twice. 2 and 3 each appear once.
4 and 1 tie on count, so compare their last appearances. 4 last appears at index 2 and 1 last appears at index 4. Index 4 is higher, so 1 ranks first and 4 ranks second.
Example 2
nums = [-1,2,-1,2,2,0]k = 3return = [2,-1,0]2 appears three times, -1 appears twice, and 0 appears once. The counts are all different, so they decide the order: 2, then -1, then 0.
0 is the last element of the array, but the last appearance only matters when two counts are equal.
Example 3
nums = [7]k = 1return = [7]7 is the only value, so it is the answer.
Constraints
1 <= nums.length <= 10^4-10^4 <= nums[i] <= 10^41 <= k, andkis at most the number of distinct values innums.
More Swiggy interview questions
Similar questions at other companies
- Filter, Sort, and Deduplicate Scheduled TasksRippling · PHONE SCREEN · ONSITE INTERVIEWRippling interview questions
- Longest Consecutive SequenceJP Morgan Chase · PHONE SCREENJP Morgan Chase interview questions
- 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
- Top K Frequent ElementsAmazon · OA · PHONE SCREEN
- Build a Pivot Table with TotalsSigma Computing · PHONE SCREEN
- Group AnagramsEPAM · PHONE SCREENEPAM interview questions