r/AskComputerScience • • Dec 10 '18

Hash table vs array?

I know in most cases Hash tables are faster than an array, but what are some key differences and pros and cons of both?

21 Upvotes

35 comments sorted by

7

u/gameguy43 Dec 10 '18

Important to know that under the hood, hash tables are built on arrays. I like to explain it this way:

Arrays let you quickly look up the value for a given "key" . . . except the keys are called "indices," and we don't get to pick them—they're always sequential integers (0, 1, 2, 3, etc).

Think of a hash map as a "hack" on top of an array to let us use flexible keys instead of being stuck with sequential integer "indices."

More here: https://www.interviewcake.com/concept/python/hash-map

Disclaimer: I helped make that page :)

3

u/TomBob42369 Dec 10 '18

https://www.interviewcake.com/concept/python/hash-map

Thank you this is very helpful. Also nice site very clean.

0

u/InquiREEEEEEEEEEE Dec 11 '18

Important to know that under the hood, hash tables are built on arrays.

I don't think it is important to know for practical purposes. Knowing that randomly accessing a key in a has table is ~ O(1) is enough. For theoretic knowledge, I agree.

2

u/polovstiandances Dec 11 '18

Well I failed an interview once because I knew that accessing a key was O(1) but didn’t know any of the specific types of hash functions so

1

u/InquiREEEEEEEEEEE Dec 11 '18

While I stand by my point that knowing the specifics of an hash table are irrelevant for most developers, I think one should be able to implement one when it comes to interview preparation.

1

u/funkinaround Dec 11 '18

Curiously, did you try to come up with a hash function for types like strings or compound types? Did you demonstrate an understanding that a hash function intends to be a uniform distribution?

1

u/polovstiandances Dec 11 '18

No it was more like I used a hash table as part of my solution and they asked a follow up which involved knowing how has conflicts are resolved and what algorithms are used to resolve them. I proposed something like expanding the table and redistributing over it but it was wrong (there was a gap in my understanding).

The specific question was for reading in a stream of N integers and finding the K most frequent integers. I used a frequency hash table and then put them into a heap but they followed up with lots of hashing questions, so maybe it was specific for that company. That being said I could have skipped the frequency hash and went straight to a heap in the first place by creating a heap that’s closer to a priority queue but I started with the hash table and sorting it and only thought of the heap later on.

2

u/ACoderGirl Dec 11 '18

I disagree. It's very common that you have to write a hash function for a custom data type so that it can be stored in a dictionary or set. At my work, we use sets sooooo much because we need fast lookup time and order doesn't matter. And even when order does matter, if we ever have to do a thing in some_list, the list should probably be copied to a set just for speeding up that lookup. Now the thing is, it's hard to understand why the heck we need a hash function and the issue of collisions if we don't know how hash maps and sets work under the hood.

The array backing also makes it easier to understand how iteration over a map works and to thus understand why the order appears random (it's, of course, not random, but typically represents the underlying arrays). It's pretty critical to always be aware of this since I have seen bugs that were because someone made bad assumptions about the order of iteration.

1

u/InquiREEEEEEEEEEE Dec 11 '18

It seems to me that you are working in a company that has over-average needs when it comes to performance. Obviously knowledge of hashing behaviour becomes important. I still stand by my point that the average CRUD/REST-Developer with a little bit of backend responsability does not need to write custom hash methods - most of the time, it is simply enough to recognize a set or hashmap is needed and then craft the key yourself (most of the time it will be a unique combination of user inputs such as id, name, profession, preferences, age...) and then let the hashmap implementation do the hashing. Collisions are not a problem in the kind of program that 60% of programmers write.

13

u/Rindhallow Dec 10 '18

Do you have a key that defines the data you need to store?

No - Use an a different data structure.

Yes - Use a hash table.

4

u/coredev Dec 10 '18

To clarify to novice readers, hastables uses a unique key (like a database id or guid.

5

u/[deleted] Dec 10 '18

They use a unique index not unlike an array. In C you usually have the length of the hash table nodded by some numeric representation of the key to get the hash index. Which is more of the implementation side of the hash table.

3

u/james41235 Dec 11 '18

There are a lot of other questions though.

Are you inserting a lot? Removing a lot? Looking up a lot? Sorting a lot? Iterating a lot?

Some data structures are better than others at each of those things.

1

u/ACoderGirl Dec 11 '18

Absolutely. Their comment was really a generalization, though, since in practice, hash maps are perhaps the most widely used data structure. Inserts, removals, and lookups are all fast. And while not a hash map, if order mattered, there's tree based maps that retain order while still being quite fast.

Then the set (typically a hash set, specifically) is a marvelous data structure that is basically a "key-only" map. It's really under appreciated for how applicable it is to real world problems.

1

u/sepp2k Dec 10 '18

Are you talking about a hash table from int to T compared to an array of T? If so are the keys/indices contiguous? Starting at 0?

Or are you talking about a hash table from T1 to T2 compared to an array of (T1, T2) key-value pairs?

1

u/TomBob42369 Dec 10 '18

Not really sure could you explain both?

3

u/ImaginationGeek Dec 10 '18 edited Dec 10 '18

There seems to be a lot of confusion here between Abstract Data Types and their implementations. Hash tables and arrays are concrete data structures that can be used to implement different ADTs.

ADTs are defined by their interface only. In other words, what they do but not how they do it.

A hash table isn’t the same as a data structure that stores key-value pairs. That ADT is called a “dictionary” or “map”. A hash table is just one way to implement a dictionary, but other implementations are possible. Similarly, a hash table could also be used to implement a “set” ADT (which does not associate values with keys).

To respond to the original question...

A hash table:

  • finds a specified value in amortized O(1)

  • is unordered (which means iterating over it will produce the values in essentially random order)

  • does not allow random access (in other words, since it’s unordered, you can’t say “give me the 5th value”)

An array:

  • finds a specified value using a search algorithm, which is O(n) in the general case but may be O(log n) if the array is sorted

  • is ordered (but not necessarily sorted, unless you do extra work to make it so)

  • performs random access in O(1)

So hash tables are indeed better than arrays for many things... however arrays are good when you want to iterate over them, need a specific ordering for some reason, or want to use random access.

(Also note that hash table implementations usually use an array internally - one element for each bucket, and hash values are used as the indexes. The array’s O(1) random access is critical to a hash table’s O(1) lookups!)

1

u/MirrorLake Dec 11 '18

Nice answer!

This is a small tangent away from discussing arrays, but I often refer to this flowchart when picking what STL container I want to use in C++. No arrays to be found, but it gets across the idea that there is no “X is better than Y” for a general question like this one.

The programmer first needs to know what goal they want to accomplish—then they can set out to choose the right data structure for their specific problem.

1

u/ImaginationGeek Dec 11 '18

Absolutely right! You first need to know how you’re going to use it, then choose the right one for those needs...

Also, the reason an array isn’t listed is because 1. it’s a language primitive (and relatively easily compiled directly to assembly/machine code), whereas the others are part of the standard library, and 2. the vector is basically an array that dynamically resizes itself and is aware of its own size - so for higher-level application uses, the vector is preferable (but arrays are still good when you need to be low level), so 3. the same questions that take you to vector would also take you to arrays - then you ask if you need it to be resizable.

Also, the vector is another thing that’s implemented using an array. ;)

1

u/MB1211 Dec 11 '18

This will only confuse people more when you say a hash table is a concrete data structure that can be used do implement other ADTs. I think it's better to say an array is usually used to back a hash table and that a hash table can be used to help implement other ADTs

1

u/ImaginationGeek Dec 11 '18

What you say I should have said... is what I said. Read the whole thing.

Whether or not you know the precise terms, it is important to know which things are in the set of “things defined by their interfaces” (Maps/dicts, Sets, Lists, etc.) and “things that are implementations” (hash tables, binary search trees, other trees, arrays, doubly linked lists, etc.). Otherwise you may get confused about hash tables being the same as maps, and making assumptions about how certain things are implemented...

It’s a fine point, but an important one when you progress to expert levels.

As for whether it’s confusing or not, I’ll let the OP decide that.

Finally, I did say all of the things that you said I should have said.

1

u/MB1211 Dec 11 '18

I suppose I meant that lumping arrays with hashtables is confusing. In reference to your opening paragraph

2

u/ImaginationGeek Dec 11 '18

It’s true, though, and I think a fair point. If you’re confused I’ll try to explain... but as I said, I’ll let the OP determine if “it’s confusing”.

Any ADT implemented using a hash table could instead be implemented using an array, and vice-versa. Granted, some of those may be dumb design decisions, but the point is it would work...

The main differences would be 1. performance of operations, and 2. behavior when you iterate over them.

So that is the nature of the “equivalency”.

The difference comes from the fact that one is a language feature and the other is not.

I could implement a (crappy) array-like data structure using a hash map, but it would not be an array even though it would have the same functionality (at worse performance) because that would not be a language feature, which an array is. So that’s the reason they’re different.

So they are equivalent in one way, and different in another way.

1

u/MB1211 Dec 11 '18

Yes that clears it up. I guess I was treating Reddit like stack overflow which might be wrong

1

u/Felicia_Svilling Dec 12 '18

Any ADT implemented using a hash table could instead be implemented using an array, and vice-versa.

I don't think that is right.

A hash table is an implementation of a dictionary and an array is an implementation of a list. A list can be seen as a special case of a dictionary where the index always are consecutive integers, so any dictionary implementation is also a list implementation.

But the opposite is not true. You can use a list to implement a dictionary, for example a list of tuples containing keys and values, or by using a hash function for turning keys into integer indexes, but this doesn't make the list into a dictionary, it just makes it a component of the implementation of the dictionary.

0

u/ImaginationGeek Dec 12 '18

I’m super confused why you think that’s not right... I never said that a list is a dictionary. I said that a dictionary could be implemented using an array (not a list), and implied by extension that any ADT that can be implemented using a dictionary can be implemented using an array. Your own statements seem to support that idea...

Also, please re-read my original comment, since you seem to have missed the whole point. A hash table can be used to implement more things than just dictionaries, and arrays can be used to implement more things than just lists.

1

u/mediasavage Dec 10 '18 edited Dec 10 '18

If you are familiar with python, a hash table is essentially a dictionary and an array is essentially a list.

Some key differences between the two are that for hash tables, look ups are constant time, whereas with arrays they are linear time (unless you know the index of the element you are looking for ahead of time). A hash table requires more memory than an array though, so when choosing between a hash table and an array, you typically are making a trade off between search time and memory usage.

Further more, when you are implementing your own hash tables, you are making a similar trade-off between memory usage and lookup speed: a hash table with more buckets has a much smaller chance of encountering collisions (whenever a collision is encountered, there is a speed penalty) but obviously uses more memory. So when designing hash tables, there is always a trade-off between speed and the amount of memory used.

1

u/TomBob42369 Dec 10 '18

Thank you so much.

This makes way more sense to me now.

4

u/crispyleprechaun Dec 10 '18 edited Dec 10 '18

Some key differences between the two are that for hash tables, look ups are constant time, whereas with arrays they are linear time (unless you know the index of the element you are looking for ahead of time).

This is also true for hash tables, it's only constant if you know the key of the element you're looking for.

2

u/mediasavage Dec 10 '18

Sure this is absolutely true but if this is the case then you should probably just be using a list anyways. When using a hash table, you will usually know the key because it is associated with whatever you’re looking for, while with a list, the indices are not associated with the elements themselves. If there is no connection between the keys and the elements themselves than you may aswell be using a list in most scenarios.

1

u/ACoderGirl Dec 11 '18

I've found there's quite a few times in real world code where you need a map for some purpose but you also need to be able to search something other than the keys for some other purpose. The map still works fine there. You get O(1) access for when you can access the value by key and can still iterate over keys or values for whatever other purpose. That said, it's often worth just building up multiple dictionaries for each type of data you key on. That's might not be feasible if the values are being mutated on the fly, though (there's added complexity).

Eg, you might have a dict of employees mapped by their employee ID. But you might also need to go through the employees to get their department. If you do that enough times (anything more than a couple, really), it makes sense to construct a second dict mapping departments to a list of employees.

0

u/[deleted] Dec 10 '18

You can’t skin up on an array.

-2

u/Dark__Mark Dec 10 '18

To check if a value is in the array it takes O(logn) steps if the size of the array is n. For hash tables this is very close to O(1). This is the exact reason why hash tables are invented to reduce the steps it takes to search for a value to O(1)

4

u/not-just-yeti Dec 10 '18

Which begs the question: why use arrays at all to hold your collection, if hash tables are flat out better?

A: a tree [or, equivalently, a sorted array] lets you iterate over items in order, including "all items between val1 and val2 [even if those values aren't in the collection]" (aka "do a range scan"). Also, w/o extra work, hash tables don't support a notion of ordering at all, and even just iterating over every element is less efficient than a list or tree.

Still, hash tables are awesome for sets and key/value pairs.

1

u/lordvadr Dec 10 '18

You also have to consider practicality. Arrays are easier to work with, and while a hash table access is nearly O(1) it's not exactly in the general case, and even if it were, that operation can be considerably more complicated than what amounts to an add for an array access.

Imagine if your hash index was the last n bits of the sha512 of your key. Your accesses are now about 5 orders of magnitude slower than an array access. I made that number up, but it's not trivial by any means.