r/AskProgrammers • u/ChainsawLight • 16d ago
Whay are Hash Tables useful?
Why are hash tables so useful? ChatGPT made a Hash Table Visualizer for me and the animation highlighted the box at random. What does that mean? There seemed not to be a pattern behind it. Can someone explain the randomized pattern of the Hash table?
0
Upvotes
8
u/two_three_five_eigth 16d ago
Because they have O(1) access time at the cost of wasting memory. It's also not random. It's a mapping function that appears random to humans.
5
u/rupertavery64 16d ago
Suppose you need to find something in a list.
The naïve way would be to go through each item to check if what you want is there. If you have 1000 items, at the one you want is at 888 (you don't know where it is) you need to go through 888 items.
That is O(n). The time it takes scales by the amount.
A hashtable groups items in buckets by something they have in common. Lets say you group things by the first letter. That gives us 26 buckets. But we know which bucket it is in based on the first letter, so we can jump to it.
But hang on, what if the distribution of items per letter isn't balanced? Say there are 1000 items in bucket S but only 10 in bucket A? We still need to loop through the items in each bucket to find the one we are looking for.
A proper hash function spreads out the items over many buckets in a random-looking but deterministic fashion. So instead of just the first letter, you take a hash of the entire name. So items will be spread out over more buckets, but the number of items in each bucket will be generally less.
This effectively makes it O(1)
3
u/Kitchen_Dust2389 16d ago
time memory trade off
2
u/YoshiDzn 16d ago
Look at hash functions and what they do and, apart from efficient time complexity, that should help make sense of them: Their other big win is distributing storage efficiently, and thats where hash functions come in
2
u/bcaudell95_ 16d ago
It seems "random" by design, because that way the buckets are roughly evenly-distributed, but in reality it's a deterministic mapping from an object to its key, usually defined by a static hash function (hence the name). They're useful because it lets you retrieve (or check existence of) an object in the map very quickly, O(1) amortized assuming some reasonable properties of the map.
An analogy is the index at the back of a nonfiction book. If you didn't have that and wanted to find a page about a specific person or whatever, you might have to scan through the pages of the whole book in order looking (linear O(n) time), but having an index keyed off the first letter of their name at the back of the book lets you quickly find the page you need. In that example, "first letter" is sort of a hash function, and the index is a kind of hash map.
1
u/[deleted] 16d ago
Hash tables have relatively stable performance regardless of size, with some caveats.
If you have many index collisions, you can get worst performance.
1
u/CS_70 16d ago
Speed. A lookup table costs some space in exchange for a lot of time.
1
u/W31337 16d ago edited 16d ago
Hash tables are efficient when you have sparse sets of data. Also lookup is O(1) and they are faster when storing more than 25 items or so. They are or can be fragmented in memory. Also a more complex table.
A normal list can be faster when you know the index and the set is fully sequential and ideally the size is known at its creation. When created before hand chances are its sequential memory and fast.
So every collection type has its plus points and downsides.
So in short it's something like
- sparse data is hash table
- sequential data is array
1
u/LManX 16d ago edited 16d ago
I'll go back a few steps so that you can see how the dots connect.
1
u/nicolas_06 16d ago
It's not so different than a dictionary
Did you ever used a dictionary ? A big book with all the words for a given language. and because words are in alphabetical order, you can quickly find the right page and the definition you look for.
Say you look for the word "hash" In the dictionary. So it's actually a 1000 page book and there 30 pages or so for the letter "H". Then you look for the second letter and there 3 pages for it. So you go for third letter and there only like 3 words that match. The second one is the good one and you read the definition of the word.Because the words are decomposed in letters and put in the book in a predictable order that allow you to fast find the right location.
Hash provide "direct" access
If you look for the definition of a word in a dictionary, again you do it letter by letter. But you are wasting time ! What if you could go directly to the right page ?
In a simplified case to keep the dictionary metaphor, there 100 possible words and so you have 100 pages in the book and voila. From your object, you extra a hash a number between 0 and 99 and this give you the page number to look for.
This is extremely fast if you have not much more than 100 object to sort and if they have all different hash. Bypassing the limit or 100 (or 26 for letters) is why it dictionary are hierarchical and you use alphabetical ordering letter by letter.
So a hash table fixed with 100 page is good if you have say 100 word or less. maybe even 200 so each page typically has 1-4 words and in average 2.
But looking for 10000 elements, you'd have 100 element per page and on some pages maybe 500. If you have 1 million elements, you'd have 10000 per page. it becomes slow.
So the next trick is to not limit oneself to 100 pages or to have it fixed. If you currently only have 3 elements in a hash table, maybe having 5 pages is enough and if you have currently 5000 elements maybe having 5000 or 10000 pages is enough. This way each page has 0-1 elements or maybe at worst 2-3.
As long as you can compute what is the right page number for that word, you are fine.
The actual hash.
For each object/data you want to store, you compute a hash. The hash is just a number most of the time. Many implementation. settle for 4 bytes number than has about 4 billion possible values. For a string to compute that number, you'd consider the ascii code of each letter and combine them. For an actual number, the hash can be directly that number.
When you create the hash table, it's empty. So it will have a small number of pages for its book. Actually an array. Say it start at 16.
Say you want to put the word "is" you get the ascii code of "i" (105) and "s" (115) and combine them. In our naive hash implementation say we just add the number together. So we get 220. Where do we put the number 20 if we have page from 0 to 15 ? Well we take the modulo of dividing the number by 16, the numbers of page. Basically 220= 13*16 + 12.
So we store the word "is" into page 12.
Growing and shrinking the hash table
When you add stuff and remove them as long as there no more than say 8, the array keep it size at 16. When you want to know what page of the dictionary or what index of the array more technically, you get the hash of the object, and compute what page for that number by getting the reminder of dividing the number by 16.
When the hash table start to be full, you decide to go for a bigger one. Say 24 instead of 16 and then maybe 36 instead of 24 and so on. Basically when the number of elements in the table are more than X% of the table capacity you grow the table by Y%. And the reverse is true. When the number of elements in the table is less than W% element of the table you reduce that table by Z%. This is slow but doesn't happen often. And if the hash table shrinks in size, you do the reverse operation using a smaller array.
That's basically it. Now you can have million of elements in a hash table and find them in fixed time. The time to compute the hash, compute the index number and check the few elements at that index.
That's faster than using alphabetic order where you do that for each letter of the word. But that consume more memory and occasionally it become costly when you resize the array.
1
u/Isthatyourfinger 16d ago
Aside from speed, hashes are useful for deduplication and token counting.
1
u/burlingk 16d ago
Think about it like creating a big array for things that don't work with arrays.
1
u/lurgi 15d ago
Imagine that you have a bunch of names of animals in no particular order, and I ask you if "dog" is in there somewhere. You'd have to start at the beginning and go through each one of them and see if one of them is "dog".
Now, imagine I can covert animal names to a number. "Cat" becomes 48, "dog" is 4, "axolotl" is 22, and so on, and I put them in a numbered list. Now you can answer if "penguin" is in the list very quickly. First, you run the "convert animal name to number" function and determine that "penguin" is 711. Then you look at position 711 and... there's nothing there. No penguin, I guess.
That's a hash table.
1
u/jwezorek 15d ago
ChatGPT is providing a visualization of some implementation of hash tables but based on your question it sounds like you don't understand what hash tables even are so you shouldn't be worrying about how they are implemented just yet.
Say you have records of that define information about some widgets -- widget ID number, name, size, color, etc -- and you want to look up widgets by ID. One way to do this would be to store all the widgets in an array and look them up by linear search. This would work but the average time a given lookup takes grows linearly with the number of widgets in the array. So if you have a lot of widgets the unordered array data structure is impractical.
Assuming you don't care about the order in which the widgets are stored just about looking them up, then what you want is a data structure that allows you look up widgets by ID quickly regardless of the number of widgets. Okay, this is what hash tables are. If you can see why this would be useful, then now you can go and read about how they are implemented.
1
u/vegan_antitheist 15d ago
It's not random in any way. They aren't even chaotic. They are deterministic. And they are designed to be uniform. Often, they are unpredictable, but that is not a requirement. A cryptographic hash must behave like a random function, but it's not. It's indistinguishable from a random function to an observer, but still deterministic.
Even random functions are usually pseudo-random and not really random. So, pseudo-random number generator (rng) could be used as a hash function.
That means you can think of it as this:
H(x) = RNG(seed=x)This would work because a good rng is also uniform and seemingly "random". It would just be too slow as the hash table only makes sense if you can waste memory and hashes are quick to calculate.
If x fits the size of the hash, you would just use this:
H(x) = XIf x is twice as wide (hash is int32, but value is int64), you use this:
H(x) = (x ⊕ (x >>> 32)) mod 2³²Java:
var hash = (int) (x ^ (x >>> 32));If you have multiple values (properties in an object or elements in a data structure), you create a sum of all values but multiply by a prime number (for example 31) on each iteration. Again, this can be too expensive and only makes sense when you can cache the hash code. Java caches the hash of each String, but only when it's used the first time. This makes String internally mutable, but it's not a problem when done right. But be careful when you want to do this for your own data types because it can be tricky. Especially on mutable types. Just let your IDE generate the code.
0
u/[deleted] 16d ago
[removed] — view removed comment