Hash tables are very common data structures used for coding problems presented in competitive programming/interviews.
Hash tables take key value pairs so that you can lookup a key and get the value. However, I often find myself needing the O(1)
lookup of a key and not really caring about the value.
For example:
If I need to know if some strings
have been used previously, I might plug them into a hash table with key: string
, value: bool
where the value of the bool is always true.
What are the down sides of doing something like this? Are there other data structures that give O(1) lookup that don't need a key value pair?
You should use a data structure the way it's intended to be used. And then you can profile your code to see if the performance is adequate. If it isn't, then optimize bottlenecks.
Having said that, a better data structure to check if a string has already been used would be std::unordered_set or std::set. Your use case is a typical use case for a set data structure. Wikipedia:
In computer science, a set is an abstract data type that can store unique values, without any particular order. It is a computer implementation of the mathematical concept of a finite set. Unlike most other collection types, rather than retrieving a specific element from a set, one typically tests a value for membership in a set.