You've successfully subscribed to Nicholas Workshop
Great! Next, complete checkout for full access to Nicholas Workshop
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

K Smallest Elements In List

Question

Write an efficient program for printing k largest elements in an array. Elements in array can be in any order.
For example, if given array is [1, 23, 12, 9, 30, 2, 50] and you are asked for the largest 3 elements i.e., k = 3 then your program should print 50, 30 and 23.

Solution

1. Sort the elements in descending order in O(nLogn)
2. Print the first k numbers of the sorted array O(k).

Code

``````def k_smallest(arr, k):
arr.sort()
for i in range(k): print (arr[i], end =" ")

arr = [1, 23, 12, 9, 30, 2, 50]
k = 3
k_smallest(arr, k)
``````
Algorithm

Nicholas Wong

Fullstack software engineer with strong background in computer science and extensive experience in software engineering and architecture. Studied in NYU, worked in Yahoo, Rakuten and Manulife.