Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient data structure for finding non-overlapping range containing a number

a data structure to store the start and endpoint of a range.

rangename      start     end

range1          10        11

range2          20        22

range3          0         5

now if i have to find the range in which a number 'x' may exist.

What would be the efficient way of storing this in c++ ?

I'm trying to use map. but then search to find the range might be expensive ( which i'm not sure of). Suggest a good data structure.

I should be able to find whether the element is present in a range or not. The ranges should not be mix and matched and no adjacent or other bounds.

If I need to a find an element 3, it is present in range 3, But an element 12 is not present at all. Just looping through cannot be an efficient way.

like image 948
King Avatar asked May 06 '26 23:05

King


2 Answers

(I have changed this answer since the asker clarified that his ranges do not overlap.)

If the set of ranges does not change, you can use a sorted vector and binary search, as suggested in ravenspoint's answer.

If the set of ranges changes over time, you might still use a sorted vector, or you might want to use a std::map. You need to try both and see which one is faster in that case.

like image 200
rob mayoff Avatar answered May 08 '26 14:05

rob mayoff


vector< pair< int>> stored sorted so you can binary search perhaps?

like image 22
Michael Dorgan Avatar answered May 08 '26 14:05

Michael Dorgan