Given **N** numbers in an array. Your task is to keep at-most **K** numbers at the top (According to their frequency). We basically need to print top k numbers when input stream has included k distinct elements, else need to print all distinct elements sorted by frequency.

**Input:**

First line consists of T test cases. First line of every test case consists of 2 integers N and K and second line of every test case consists of elements of array.

**Output:**

Single line output, print the atmost top K elements of the array.

**Constraints:**

1 <= T <= 10^{3}

1 <= N, K <= 10^{6}

**Example:
Input:**

2

5 4

5 2 1 3 2

5 4

5 2 1 3 4

5 2 5 1 2 5 1 2 3 5 2 1 3 5

5 2 5 1 2 5 1 2 3 5 1 2 3 4

**Explanation:**

**For 1st test case:**

arr[] = 5 2 1 3 2

Firstly their was 5 whose frequency is max till now. so print 5.

Then 2 , which is smaller than 5 but their frequency is same so print 2 5.

Then 1, Which is smallet among all the number arrived, so print 1 2 5.

Then 3 , so print 1 2 3 5

Then again 2, which has the highest frequency among all number so 2 1 3 5.

**For 2nd test case:**

arr[] = 5 2 1 3 4

Firstly their was 5 whose frequency is max till now. so print 5.

Then 2 , which is smaller than 5 but their frequency is same so print 2 5.

Then 1, Which is smallest among all the number arrived, so print 1 2 5.

Then 3 , so print 1 2 3 5.

Then 4, so 1 2 3 4 as K is 4 so print at-most k elements.

Author: saksham seth

If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.

saiujwal13083 | 347 |

isiddhisingh | 252 |

Abhishek_Jadhav | 243 |

_uncle_sam_ | 221 |

c_ocoooo | 217 |

saiujwal13083 | 610 |

SumitSingh27 | 466 |

c_ocoooo | 456 |

rathiarpit29 | 379 |

NaveenKumarNakka | 370 |

blackshadows | 5362 |

Ibrahim Nash | 5242 |

akhayrutdinov | 5111 |

mb1973 | 4931 |

Quandray | 4598 |

Login to report an issue on this page.