Top-N Per Group

MediumData EngineeringArrayMathSorting

Description

Given an array of [key, value] pairs and an integer n, return [key, topValues] for each distinct key, where topValues lists that key’s n largest values in descending order. Keys are ordered by first appearance.

Examples

Input:[[1,5],[1,9],[1,2],[2,7]], 2
Output:[[1,[9,5]],[2,[7]]]
Explanation:

Within each key the values are sorted from high to low and the requested number of the largest are returned.

Input:[[1,1],[1,2],[1,3]], 1
Output:[[1,[3]]]
Explanation:

Within each key the values are sorted from high to low and the requested number of the largest are returned.

Input:[[5,4],[5,4]], 2
Output:[[5,[4,4]]]
Explanation:

Within each key the values are sorted from high to low and the requested number of the largest are returned.

Constraints

  • 1 ≤ pairs ≤ 10⁴
  • 1 ≤ n

Ready to solve this problem?

Practice solo and sharpen your skills for technical interviews.