Search code examples
algorithmlistconstant-time

How to lookup an integer in an N sized list in constant time?


Properties of the list:

  1. must be of size N, where N is the amount of integers

  2. no empty cells

  3. numbers may not be perfectly sequential (i.e. {-23,-15,-3,1,2,6,7,8,15,100})

  4. Insertion/Lookup needs to be in constant time.

My first instinct was to use a hash table, but this would create unused cells where numbers are skipped.

Is there any way such a list can be constructed to check in constant time if a number exists in that list?


Solution

  • Following my comments, you can go with a Set, depending on your exact use case you can check out things like Java's HashSet or LinkedHashSet if you need to maintain the order which according to the doc is supposed to be constant time:

    Like HashSet, it provides constant-time performance for the basic operations (add, contains and remove), assuming the hash function disperses elements properly among the buckets.

    If you are looking for solutions on other platforms maybe there are equivalent implementations or you can check Java's source code and implement it yourself.