InterviewBit Academy is now Scaler!
InterviewBit Academy is now Scaler Academy!

Numbers with most occurences

Problem Description

Given an integer array A of size N and a positive integer B. Find B numbers with most occurrences, i.e., the top B numbers having the maximum frequency.

If two numbers have the same frequency then the larger number should be given preference. The numbers should be displayed in decreasing order of their frequencies.

NOTE: It is assumed that the array consists of B numbers with most occurrences.

Problem Constraints

1 <= N <= 105

1 <= B <= N

1 <= A[i] <= 109

Input Format

First argument is an integer array A.

Second argument is an integer B.

Output Format

Return an integer array denoting the top B numbers having the maximum frequency.

Example Input

Input 1:

 A = [3, 1, 4, 4, 5]
 B = 2

Input 2:

 A = [1, 1, 1, 4, 4]
 B = 2

Example Output

Output 1:

 [4, 5]

Output 2:

 [1, 4]

Example Explanation

Explanation 1:

 Frequency of element 4 is 2 and all others element have frequency 1.
 First element will be 4 and second element will be 5 (Since it is largest among [1, 3, 5]).

Explanation 2:

 Frequency of element 1 is 3 and element 4 have frequency 2.
 First element will be 1 and second element will be 4.

NOTE: You only need to implement the given function. Do not read input, instead use the arguments to the function. Do not print the output, instead return values as specified. Still have a doubt? Checkout Sample Codes for more details.
Start solving Numbers with most occurences on Interview Code Editor
Sign Up
to access hints and editorial solutions for Numbers with most occurences


Click here to start solving coding interview questions