IBM Interview Questions
Qu1: What is hashing and how it works???
Answer: Hashing means using some function or algorithm to map object data to some representative integer value. This so-called hash code (or simply hash) can then be used as a way to narrow down our search when looking for the item in the map.
How hashing works
Purely as an example to help us grasp the concept, let's suppose that we want to map a list of string keys to string values (for example, map a list of countries to their capital cities). So let's say we want to store the data in Table 1 in the map.Key | Value |
---|---|
Cuba | Havana |
England | London |
France | Paris |
Spain | Madrid |
Switzerland | Berne |
Position (hash code = key length) | Keys array | Values array |
---|---|---|
1 | ||
2 | ||
3 | ||
4 | Cuba | Havana |
5 | Spain | Madrid |
6 | France | Paris |
7 | England | London |
8 | ||
9 | ||
10 | ||
11 | Switzerland | Berne |
We can also easily see that this method wouldn't work for storing arbitrary strings. If one of our string keys was a thousand characters in length but the rest were small, we'd waste the majority of the space in the arrays. More seriously, this model can't deal with collisions: that is, what to do when there is more than one key with the same hash code (in this case, one than more string of a given length). For example, if our keys were random words of English, taking the string length would be fairly useless. Granted, the word psuedoantidisestablishmentarianistically would probably get its own place in the array. But on the other hand, we'd be left with thousands of, say, 6-letter words all competing for the same slot in the array
Comments
Post a Comment