Top K Frequent Elements
Updated
Problem statement
You are given an integer array nums and an integer k. Return the k distinct values that occur most frequently.
The selected set is guaranteed to be unique. For deterministic output, list selected values by decreasing frequency; when two selected values have the same frequency, list the smaller value first.
Function
topKFrequent(nums: int[], k: int) → int[]Examples
Example 1
nums = [1,1,1,2,2,3]k = 2return = [1,2]The frequencies are three for 1, two for 2, and one for 3.
Example 2
nums = [4,4,-1,-1,2]k = 2return = [-1,4]Both selected values occur twice, so the smaller value comes first.
Constraints
1 <= nums.length <= 100000-10000 <= nums[i] <= 100001 <= k <=the number of distinct values innums.- The set of
kmost frequent values is unique.
More Infosys Onsite Interview questions
- Minimum Coins for a TargetONSITE INTERVIEW · Seen Nov 2026
- Delete Duplicate Employee RecordsONSITE INTERVIEW · Seen Nov 2026
- Find Duplicate Employee RecordsONSITE INTERVIEW · Seen Nov 2026
- Minimum Insertion Steps to Make a String PalindromeONSITE INTERVIEW · Seen Nov 2026
- Maximize the Even-Odd Index Product GapONSITE INTERVIEW · Seen Oct 2026
- Minimum Nonadjacent Flips for an Alternating Binary StringONSITE INTERVIEW · Seen Oct 2026
- Tenth-Highest Distinct SalaryONSITE INTERVIEW · Seen Oct 2026
- Assign Cookies With Matching ParityONSITE INTERVIEW · Seen Sep 2026
- Count Equal Code Pairs Within Distance KONSITE INTERVIEW · Seen Sep 2026
- Daily Successful Transactions Per DepartmentONSITE INTERVIEW · Seen Sep 2026
Similar questions at other companies
- Top K Frequent ElementsAmazon · OA · PHONE SCREEN · ONSITE INTERVIEW
- Mutual-Friend RecommendationsMeta · PHONE SCREEN · ONSITE INTERVIEW
- Top K Frequent ElementsCapgemini · ONSITE INTERVIEW
- Top K Frequent Elements with Larger-Value Tie BreakOracle · ONSITE INTERVIEW
- Stable Top K Frequent WordsGoogle · PHONE SCREEN · ONSITE INTERVIEW
- Top K Frequent ElementsBloomberg LP · ONSITE INTERVIEW
- Rearrange Songs by AuthorZomato / Eternal · OA
- Top K Frequent ElementsApple · PHONE SCREEN
- Top K Frequent ElementsC3.ai · PHONE SCREEN
- Smallest Range Covering Elements from K ListsSnap Inc. · PHONE SCREEN