Find K-th smallest element in an array for multiple queries

Given an array arr[] of size N and an array Q[][] consisting of M queries that needs to be processed on the given array. It is known that these queries can be of the following two types:

  • Type 1: If Q = 1, then add an element in the array {type, element_to_add}.
  • Type 2: If Q = 2, then print the K-th smallest element in the array. {type, k}

The task is to perform the given queries such that the following constraints are given:

  • 1 ≤ Number of queries ≤ 1000000.
  • 1 ≤ N ≤ 1000000.
  • 1 ≤ arr[i] ≤ 100000000. And, the array can contain duplicate entries.

Examples:

Input: arr[] = {1, 2, 3, 4, 5, 6}, Q[][] = {{1, 7}, {2, 4}, {1, 5}, {2, 6}}
Output: 4 5
Explanation:
The first query is used to add 7 in the array. The array arr[] becomes: {1, 2, 3, 4, 5, 6, 7}
The second query is to find 4th smallest element. It is 4 in this case.
The third query is used to add 5 in the array. The array arr[] becomes: {1, 2, 3, 4, 5, 5, 6, 7}
The fourth query is to find 6th smallest element. It is 5 in this case.

Input: arr[] = {2, 4, 2, 1, 5, 6, 2, 4}, Q[][] = {{1, 3}, {2, 2}, {1, 10}, {2, 7}}
Output: 2 4



Naive Approach: The naive approach for this problem is to add the element in the array and sort the array for every first type of query. And, whenever the second type of query occurs, print the K-th element in the sorted array.

Time complexity: O(M * (Nlog(N))) where M is the number of queries and N is the size of the array.

Efficient Approach: The idea is to use a policy-based data structure. For this problem, we can use order_of_key datastructure to find the K-th smallest element in the array.

  • The order_of_key() is a builtin function of Ordered Set which is a Policy Based Data Structure in C++. Policy-based data structures are not part of the C++ standard library but g++ compiler supports them. This data structure finds the K-th smallest element in logarithmic time complexity.
  • However, this data structure doesn’t allow duplicate keys. In order to use the data structure for duplicate elements, a pair is used.
  • We create a pair of the given element and index number to insert it in the policy-based data structure.
  • The pairs are first sorted by comparing the first element than the second. For example, (2, 1) is ordered before (2, 7).

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find K-th
// smallest element in an array
// for multiple queries
  
#include <bits/stdc++.h>
using namespace std;
  
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
  
template <class T>
  
// Defining the policy-based data
// structure
using oset
    = tree<T, null_type,
           less<T>, rb_tree_tag,
           tree_order_statistics_node_update>;
  
// Function to find K-th
// smallest element in an array
// for multiple queries
void Operations(int arr[], int n,
                int query[][2], int k)
{
  
    // Declare the data structure that
    // stores the pairs
    oset<pair<int, int> > s;
  
    int j = 0;
    // Loop to insert the inital array
    // elements into the set
    for (j = 0; j < n; j++) {
        s.insert({ arr[j], j });
    }
  
    // Loop to process the queries
    for (int i = 0; i < k; i++) {
        if (query[i][0] == 1) {
  
            // Inserting the element if the
            // type of query is 1
            s.insert({ query[i][1], j });
            j++;
        }
  
        // Finding the K-th smallest element
        // if the type of the query is 2
        else if (query[i][0] == 2) {
            cout << (*s
                          .find_by_order(
                              query[i][1] - 1))
                        .first
                 << endl;
        }
    }
}
  
// Driver code
int main()
{
    int n = 8;
    int arr[] = { 2, 4, 2, 1, 5, 6, 2, 4 };
  
    int k = 4;
    // Queries. The first element denotes
    // the type of the query
    int query[4][2] = { { 1, 3 },
                        { 2, 2 },
                        { 1, 10 },
                        { 2, 7 } };
  
    Operations(arr, n, query, k);
  
    return 0;
}

chevron_right


Output:

2
4

Time Complexity: O(M * log(N)), where M is the number of queries and N is the size of the array.

competitive-programming-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.