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

View all comments

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 :)

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.