The Wayback Machine - https://web.archive.org/web/20240624013518/https://www.geeksforgeeks.org/kth-smallestlargest-element-using-stl/
Open In App

K’th Smallest/Largest Element using STL

Last Updated : 08 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array and a number k where k is smaller than size of array, we need to find the k’th smallest element in the given array. Examples:

Input : arr[] = {7, 10, 4, 3, 20, 15}
            k = 2
Output : 4
Smallest element is 3. Second smallest
is 4.

Input : arr[] = {7, 10, 4, 3, 3, 15}
            k = 2
Output : 4
Even if there are more than one occurrences
of 3, answer should be 4.

Input :arr[] = {7, 10, 4, 3, 20, 15}
          k = 4
Output : 10

We use set in C++ STL. 1) Insert all elements into a set. 2) Traverse the set and print k-th element. 

Implementation:

C++




// STL based C++ program to find k-th smallest
// element.
#include <bits/stdc++.h>
using namespace std;
 
int kthSmallest(int arr[], int n, int k)
{
// Insert all elements into the set
set<int> s;
for (int i = 0; i < n; i++)
s.insert(arr[i]);
 
// Traverse set and print k-th element
auto it = s.begin();
for (int i = 0; i < k - 1; i++)
it++;
return *it;
}
 
int main()
{
int arr[] = { 12, 3, 5, 7, 3, 19 };
int n = sizeof(arr) / sizeof(arr[0]), k = 2;
cout << "K'th smallest element is "
<< kthSmallest(arr, n, k);
return 0;
}


Java




import java.util.Set;
import java.util.TreeSet;
 
public class KthSmallest {
    public static int kthSmallest(int[] arr, int n, int k) {
        // Insert all elements into the set
        Set<Integer> s = new TreeSet<Integer>();
        for (int i = 0; i < n; i++) {
            s.add(arr[i]);
        }
 
        // Traverse set and print k-th element
        int i = 0;
        for (Integer num : s) {
            if (i == k - 1) {
                return num;
            }
            i++;
        }
        return -1;
    }
 
    public static void main(String[] args) {
        int[] arr = {12, 3, 5, 7, 3, 19};
        int n = arr.length, k = 2;
        System.out.println("K'th smallest element is " + kthSmallest(arr, n, k));
    }
}


Python3




# STL based python program to find k-th smallest
# element.
from sortedcontainers import SortedList, SortedSet, SortedDict
 
def kthSmallest(arr, n, k) :
    # Insert all elements into the set
    s=SortedSet();
    for i in range(0,n):
        s.add(arr[i]);
     
    # Traverse set and print k-th element
    i=1;
    ans=-1;
    for val in s:
        if(i==k):
            ans=val;
            break;
        i+=1;
 
    return ans;
 
arr = [ 12, 3, 5, 7, 3, 19 ];
n = len(arr);
k = 2;
print("K'th smallest element is ",kthSmallest(arr, n, k));


C#




using System;
using System.Linq;
using System.Collections.Generic;
 
class KthSmallest
{
    public static int kthSmallest(int[] arr, int k)
    {
        // Insert all elements into the set
        var s = new SortedSet<int>(arr);
 
        // Traverse set and print k-th element
        return s.ElementAt(k - 1);
    }
 
    public static void Main(string[] args)
    {
        int[] arr = { 12, 3, 5, 7, 3, 19 };
        int k = 2;
        Console.WriteLine("K'th smallest element is " + kthSmallest(arr, k));
    }
}


Javascript




// Javascript program to find k-th smallest element.
 
function kthSmallest(arr, n, k)
{
// Insert all elements into the set
    let s= new Set();
    for (let i = 0; i < n; i++)
    s.add(arr[i]);
     
    // Traverse set and print k-th element
    let i = 0;
    for (const entry of s.values())
    {
        if(i==k)
        {
            i=entry;
            break;
        }
        i++;
    }
         
    return i;
}
 
let arr = [ 12, 3, 5, 7, 3, 19 ];
let n = arr.length, k = 2;
document.write("K'th smallest element is "+ kthSmallest(arr, n, k));


Output

K'th smallest element is 5

Time complexity: O(n Log n). Note that set in STL uses a self-balancing BST internally and therefore time complexity of search and insert operations is O(log n). 
Auxiliary Space: O(n) where n is size of array, since n extra space has been taken.

Related Posts : 
K’th Smallest/Largest Element in Unsorted Array | Set 1
K’th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time K’th Smallest/Largest Element in Unsorted Array | Set 3 (Worst Case Linear Time)



Similar Reads

Remaining array element after repeated removal of last element and subtraction of each element from next adjacent element
Given an array arr[] consisting of N integers, the task is to find the remaining array element after subtracting each element from its next adjacent element and removing the last array element repeatedly. Examples: Input: arr[] = {3, 4, 2, 1}Output: 4Explanation:Operation 1: The array arr[] modifies to {4 - 3, 2 - 4, 1 - 2} = {1, -2, -1}.Operation
8 min read
How to find the maximum element of an Array using STL in C++?
Given an array arr[], find the maximum element of this array using STL in C++.Example: Input: {1, 45, 54, 71, 76, 12} Output: 76 Input: {1, 7, 5, 4, 6, 12} Output: 12 Approach: Max or Maximum element can be found with the help of *max_element() function provided in STL.Syntax: *max_element (first_index, last_index); C/C++ Code // C++ program to fin
1 min read
How to find the maximum element of a Vector using STL in C++?
Given a vector, find the maximum element of this vector using STL in C++. Example: Input: {1, 45, 54, 71, 76, 12} Output: 76 Input: {1, 7, 5, 4, 6, 12} Output: 12 Approach: Max or Maximum element can be found with the help of *max_element() function provided in STL. Syntax: *max_element (first_index, last_index); C/C++ Code // C++ program to find t
1 min read
How to find the minimum and maximum element of an Array using STL in C++?
Given an array arr[], find the minimum and maximum element of this array using STL in C++.Example: Input: arr[] = {1, 45, 54, 71, 76, 12} Output: min = 1, max = 76 Input: arr[] = {10, 7, 5, 4, 6, 12} Output: min = 4, max = 12 Approach: Min or Minimum element can be found with the help of *min_element() function provided in STL.Max or Maximum elemen
2 min read
How to find the minimum and maximum element of a Vector using STL in C++?
Given a vector, find the minimum and maximum element of this vector using STL in C++. Example: Input: {1, 45, 54, 71, 76, 12}Output: min = 1, max = 76Input: {10, 7, 5, 4, 6, 12}Output: min = 4, max = 12Approach: Min or Minimum element can be found with the help of *min_element() function provided in STL.Max or Maximum element can be found with the
2 min read
Find Maximum and Minimum element in a Set in C++ STL
Given a Set, the task is to find the maximum and minimum element of this set in C++ STL. Examples: Input: set={1, 6, 15, 10, 5} Output: max = 15, min = 1 Input: set={10, 20, 30, 40, 50, 60} Output: max = 60, min = 10Using set.begin() and set.end() methods Approach: Elements in a set are stored in sorted order. So the minimum element of the set will
3 min read
How to delete last element from a List in C++ STL
Given a List, the task is to remove the last element from this List in C++. Examples: Input: list = [10 20 30 70 80 90 100 40 50 60] Output: 10 20 30 40 50 60 70 80 90 Input: list = [1 2 3 4 5] Output: 1 2 3 4 Lists are a type of associative containers in which each element has to be unique because the value of the element identifies it. The value
3 min read
Get Map Element at Offset in C++ STL
Prerequisites: Map in C++ STL Since the map is not indexed as arrays or vectors sequential access is not possible in the map but to access an element at a particular offset. Example: inserted elements are { 'a',11 } , { 'b',12 } , { ' c ', 13 } then we can get { 'b', 12 } for 2 position. Methods to Get Map Element at Offset in C++ STL Using an iter
3 min read
Different Ways to Remove an Element From Set in C++ STL
Prerequisite: Set in C++ There are multiple ways to remove an element from the set. These are as follows: Removing an element by its valueRemoving an element by its indexRemoving an element by an iterator Example: Input set s={10, 20, 30, 40, 50} , value=40 // Removing 40 from the set Output set s={10, 20, 30, 50} 1. Removing an element by its valu
3 min read
Largest element smaller than current element on left for every element in Array
Given an array arr[] of the positive integers of size N, the task is to find the largest element on the left side of each index which is smaller than the element present at that index. Note: If no such element is found then print -1. Examples: Input: arr[] = {2, 5, 10} Output: -1 2 5 Explanation : Index 0: There are no elements before it So Print -
11 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg