0

I'm getting a stream of positive integers to my program. I've to store them as I receive them and be able to answer to range queries that come in between.

A simple solution that came to my mind is to store integers in a hashtable where keys are character representation of the integers(keys must be strings in my hashtable). Then, whenever a range query [a, b] comes, I can simply loop from a to b, check whether key exists and retrieve the value if it does. However, I'm not sure if this is a good approach.

What other alternative solutions exists for this problem?

SpiderRico
  • 1,890
  • 8
  • 28
  • 48

1 Answers1

0

If you maintained an ordered list of the integers from the stream read so far, then a range query can be done by finding a (using binary search) and iterating from that point until you pass b, so that the time spent on the query will be proportional to the actual size of the result, regardless of how sparse the range is filled.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • This is a valid alternative and I will try it but can we say this is strictly better than my naive solution? This one has a insertion time, right? – SpiderRico Jun 18 '18 at 17:10
  • You'd need a pretty contrived or trivially-sized problem for this to not be better. – Scott Hunter Jun 18 '18 at 17:13
  • 1
    @SpiderRico how about using a balanced search tree like AVL tree where the insertion time will be log(n) ? – zenwraight Jun 18 '18 at 17:14