How to check if an integer is in a set of given ranges? [closed]

The time efficient way to do this is to create a Bitset with a bit set for all of the integers in all of the sets. Then you can test for membership with a single O(1) call.

The problem is that if the combined range of the integers is large, then the Bitset will take a lot of memory.

A second approach is to combine overlapping ranges, and construct a TreeMap<Integer, Integer> where the key is the lower bound and value is the upper bound of each combined range. Then use TreeMap::floorKey and a test to find the matching ranges. This procedure is O(logN) where N is the number of combined ranges. Space usage will be O(N).

Leave a Comment