THINK FIRST·CODE LATER

← All labs

Top-k and the k-th largest value

Problem

Read n integers and report the k largest of them and the k-th largest, using a min-heap that never holds more than k elements (java.util.PriorityQueue is allowed). Do not sort the whole input.

Input. The first line holds n and k. The next line(s) hold n integers (possibly negative, possibly repeated).

Output. If k < 1 or k > n (this includes n = 0), print exactly Invalid k. Otherwise print two lines:

Top k: v1 v2 ... vk
Kth largest: x

where v1 … vk are the k largest values in descending order and x is the k-th largest. Duplicates count separately: the 2 largest of 5 5 3 are 5 5, so the 2nd largest is 5.

Example.

Input:
7 3
7 2 9 4 9 1 6

Output:
Top 3: 9 9 7
Kth largest: 7

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d11-2-data-1.txt

7 3
7 2 9 4 9 1 6
What your program must print for d11-2-data-1.txt
Top 3: 9 9 7
Kth largest: 7

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d11-2-data-1.txt

Windows PowerShell does not understand <:

Get-Content d11-2-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.