FastPrepTop K Frequent Elements
Problems/Top K Frequent Elements

Top K Frequent Elements

Capgemini logoCapgemini● MediumFULLTIMEONSITE INTERVIEW
QuestionFunctionExamplesConstraints

Problem statement

Source note: The reported task identifies this standard algorithmic exercise. The executable interface, bounds, deterministic tie rules, and examples are the documented practice contract.

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] <= 10000
  • 1 <= k <= the number of distinct values in nums.
  • The set of k most frequent values is unique.

More Capgemini problems

  • Most Recent Order for Each CustomerONSITE INTERVIEW · Seen Oct 2026
  • Contains DuplicatePHONE SCREEN · Seen Sep 2026
  • Detect a Linked-List CycleONSITE INTERVIEW · Seen Sep 2026
All Capgemini interview questionsSee Capgemini hiring insights
Saved
class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        // Write your code here.
    }

}
Checking account…