Top K Smallest Elements
EasyPractice library · +10 XPheapspriority queuestop-k
Given a list of N integers, find and print the K smallest elements in the list. If there are duplicate values, include them. The elements should be printed in non-decreasing order.
Input
The first line contains two integers N and K, separated by a space. The second line contains N integers, representing the list of numbers.
Output
Print the K smallest integers, separated by spaces, in non-decreasing order.
Constraints
1 <= K <= N <= 1000. Each integer in the list will be between -10^9 and 10^9.
Time limit 1 s (native code; slower languages get more)Memory 256 MB13 hidden tests
Example 1
Input
5 3 10 4 8 2 6
Output
2 4 6
The 3 smallest elements are 2, 4, 6.
Example 2
Input
7 4 5 5 5 1 1 8 8
Output
1 1 5 5
The 4 smallest elements are 1, 1, 5, 5.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
Example 1 input
5 3 10 4 8 2 6
Example 2 input
7 4 5 5 5 1 1 8 8