Consider I have a set of intervals described by [min, max]
pairs. I want to find all sets of intervals which contain a given value.
I made this solution which works in O(n) time and serves as an example of what I'm after:
#include <iostream>
#include <vector>
using namespace std;
struct data
{
int minValue;
int maxValue;
};
void searchValue(const vector<data> &v, int target)
{
for(size_t i = 0; i < v.size(); i++)
{
if(target >= v[i].minValue && target <= v[i].maxValue)
cout << "Found target at set " << i << " (" << v[i].minValue << "," << v[i].maxValue << ")" << endl;
}
}
int main()
{
data d1 = {-1, 0};
data d2 = {0, 3};
data d3 = {-1, 5};
data d4 = {10, 11};
data d5 = {9, 12};
// Vector to hold the interval sets
vector<data> v{d1, d2, d3, d4, d5};
// Search for the interval sets which contain the number 2
searchValue(v, 2);
return 0;
}
It's very important I find all possible sets, not just one.
I'm now looking for a solution which is more computationally efficient, possibly in logarithmic time. I think there may be a solution with multiset/multimap, lower_bound/upper_bound, etc., but I haven't had any success so far.
This can be achieved using interval trees but I believe there might a solution using just the STL.