Given N input integers, and M query ranges, output the set of integers that fall within each query range (both bounds are inclusive). For example:
N = [-10, -1, -2, 0, 0, 8, 12, 16]
M = [(-100, 0), (2, 5), (13, 18)]
The answer/output would then be:
[-10, -1, -2, 0, 0]
[]
[16]
I've been trying to think of optimal solutions to this, and am struggling to come up with something that's better than O(N*M) at worst case. The approaches I've considered so far are:
Brute Force - For each query, check every digit in N and see if it falls within the range.
Presorted Input - Sort the input digits (O(NlogN)), and then do the above. Can do bounds checks for queries that are completely out of range, and remove the need to iterate (i.e. querying (0, 2) for a list like [5, 6, 7]). This still involves iterating though, and at worst case is still O(NM) (right?)
Hash Set - Add each value in the input array into a hash set, and then for each possible integer value within the query range, check if it exists in the hash set. This works for smaller ranges, but basically is the same thing -> it's O(MX) where X is the length of the query range. So if you have a query range that's huge (i.e. (-10000000, 10000000)), it wouldn't scale.
I would love to hear/learn about solutions that are better! (An alternative to this question is determining the # of digits that are within each query range, as opposed to outputting the digits).
Please let me know!