Find Right Interval in C++


Suppose we have a of intervals, for each of the interval i, check whether there exists an interval j whose start point is bigger than or equal to the endpoint of the interval i, which can be called that j is on the "right" of i. For any interval i, we have to store the minimum interval j's index, which indicates that the interval j has the minimum start point to build the "right" relationship for interval i. When the interval j doesn't exist, then store -1 for the interval i. And finally, we need output the stored value of each interval as an array. So if the input is like [[3,4], [2,3], [1,2]], so the output will be [-1, 0, 1], as there are no such right interval for [3, 4], For interval [2,3], the interval [3,4] has minimum-"right" start point; And for [1,2], the interval [2,3] has minimum-"right" start point.

To solve this, we will follow these steps −

  • n := size of intervals array, create am array ret of size n, and fill this using -1, crate a map called m

  • for i in range 0 to size of intervals

    • if intervals[i, 0] is in m, then skip to the next interval

    • m[intervals[i, 0]] := i + 1

  • for i in range n – 1 down to i >= 0

    • it := point to that key-value pair which has the smallest key, but not smaller than intervals[i, 1]

    • if the value of it is 0, then go for the next iteration

    • ret[i] := value of it – 1

  • return ret

Example (C++)

Let us see the following implementation to get a better understanding −

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   vector<int> findRightInterval(vector<vector<int>>& intervals) {
      int n = intervals.size();
      vector <int> ret(n, -1);
      map <int, int< m;
      for(int i = 0; i < intervals.size(); i++){
         if(m.count(intervals[i][0])) continue;
         m[intervals[i][0]] = i + 1;
      }
      for(int i = n - 1; i >= 0; i--){
         map <int, int> :: iterator it = m.lower_bound(intervals[i][1]);
         if(it->second == 0) continue;
         ret[i] = it->second - 1;
      }
      return ret;
   }
};
main(){
   vector<vector<int>> v = {{3,4},{2,3},{1,2}};
   Solution ob;
   print_vector(ob.findRightInterval(v));
}

Input

[[3,4],[2,3],[1,2]]

Output

[-1,0,1]

Updated on: 29-Apr-2020

261 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements