How to find k^th smallest element from 1-D array. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to find k^th smallest element from 1-D array.

20th Jan 2022, 4:23 PM
Vinit Kumar.
Vinit Kumar. - avatar
6 Answers
+ 1
1. Sort the array in ascending order. 2. Remove duplicate values. 3. Get the k-th element from the array.
20th Jan 2022, 4:26 PM
Ipang
+ 1
Ipang , better: 2. 1. 3.
20th Jan 2022, 5:07 PM
Shadoff
Shadoff - avatar
+ 1
Shadoff, Isn't duplicate removal easier when the array is sorted?
20th Jan 2022, 5:13 PM
Ipang
+ 1
Ipang , l = [3,5,3,1,2,4,5] l2 = list(set(l)) and then sorting and then getting k-th element
20th Jan 2022, 5:17 PM
Shadoff
Shadoff - avatar
+ 1
Shadoff, Yes that is the right way in Python. I guess things are different by language. In C++ std::unique() works best with sorted collections. So maybe implementation differ by language : )
20th Jan 2022, 5:25 PM
Ipang
+ 1
Thank you, Guys.
20th Jan 2022, 6:02 PM
Vinit Kumar.
Vinit Kumar. - avatar