I’m studying for future interviews and I wanted to know something.
I have an array of six strings, and I want to know if there is some way
to find one of them in O(1) like a Hash table.
For example, suppose that we have the following strings in advance.
char* massageOp[6] = {"SIL","TAG","SILA","TAGS","AVS", "AVST"};
Now the user gives me one string, any string, and I want to know If I can find the string in my array, or no, in O(1). Is there any way to do this, or I need to pass through all the array to find it out?
Thanks.
It depends on how you define O(1) just as Oli mentioned. If you want an EXPECTED O(1) (recall that hash-table may have collisions and it’s difficult to estimate a worst-case complexity) time complexity in the number of strings. It would be easy to use some good string hashing algorithms to solve the problem, for example, we may use ELFHash:
Using this ELFHash function with your string as “key” and a large prime number as “M”, you can get an integer value which is the hash value of your string. You can also use some other string hashing functions and you can find some discussions here: Hashing Tutorial