Skip to content
Related Articles

Related Articles

Improve Article

Kth smallest pair and number of pairs less than a given pair (x, y)

  • Last Updated : 20 Jul, 2021
Geek Week

Given N pairs, the task is to find the Kth smallest pair and the number of pairs less than the given pair (x, y).

Examples:

Input: pairs[][] = {{23, 20}, {23, 10}, {23, 30}, {12, 35}, {12, 22}}, K = 3, (x, y) = (23, 20)
Output:
{23, 10}
3

Input: pairs[][] = {{23, 20}, {23, 10}, {23, 30}, {12, 35}, {12, 22}}, K = 2, (x, y) = (12, 35)
Output:
{12, 35}
1

Naive Approach: The above problem can be solved by finding all pairs from array, and then printing the Kth smallest pair and the count of pairs less than (x, y) respectively.



Policy Based Data Structure Approach: Following is a code showing policy-based data structure as MAP. It can add/remove pair of elements, can find the number of pairs less than (x, y), Kth smallest pair, etc in O(log N) time. The specialty of this map is that we have access to the indices that the pair of elements would have in a sorted 2D array. If the pair does not appear in the map, we get the position that the pair would have in the map.




// C++ implementation of the approach
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <functional>
#include <iostream>
using namespace __gnu_pbds;
using namespace std;
  
// A new data structure is defined
// Please refer https:// goo.gl/WVDL6g
typedef tree<pair<int, int>, null_type,
             less<pair<int, int> >,
             rb_tree_tag, tree_order_statistics_node_update>
    ordered_map;
  
// Driver code
int main()
{
    ordered_map om;
  
    om.insert({ 23, 20 });
    om.insert({ 23, 10 });
    om.insert({ 23, 30 });
    om.insert({ 12, 35 });
    om.insert({ 12, 22 });
  
    int K = 2, x = 12, y = 35;
  
    cout << "{" << om.find_by_order(K - 1)->first << ", "
         << om.find_by_order(K - 1)->second << "}\n";
  
    cout << om.order_of_key({ x, y }) << endl;
  
    return 0;
}
Output:
{12, 35}
1

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :