45 points · by techdog · 17y ago · 78 comments
We're hashing a million words into a table that can hold four billion. The load factor on the table is negligible. If we're getting collisions it means we need a better hash algorithm.
There is absolutely no excuse for using a hash table without understanding the birthday paradox. If you hash a million words to four billion values, you WILL get hash collisions -- a few hundred of them.
The author is right about one thing, though; this is a good interview question. It identified him as someone who picked a poor algorithm yet didn't even understand that algorithm properly, marking him -- in my opinion at least -- as an immediate no-hire.
I'm somewhat amazed that he could answer it even to the extent he did. Most tech writers I've worked with do not have the (apparent) level of technical knowledge this guy has.
The grand parent is right, this is a horrible programming solution but the author is not a programmer!
(((A * 27) + B) * 27)+C) then a datastructure for count and the next Hash table if needed. Use this recursivly and you can handel just about any word and get there with (Length/3) looks at main memory. And you can still alocate all that memory in a few large chunks so that's still fast.
Then optomize for speed or memory as need. (If you don't mind sacrificing space you use 32bits per letter and then bit shift etc.)
Assuming the corpus is not too big, the solution can be thrown together in Python in a few minutes.
import re, collections
def words(text): return re.findall('[a-z]+', text.lower())
def train(features):
model = collections.defaultdict(lambda: 1)
for f in features:
model[f] += 1
return model
NWORDS = train(words(file('corpus.txt').read()))
import heapq, operator
freq_words = heapq.nlargest(10000, NWORDS.iteritems(), key=operator.itemgetter(1))
This code processes 12Mb of text in less than 5 seconds on my laptop.The tree structure: Put all the unique words into a tree. You could use a trie, but considering how dense the tree is likely to end up, a traditional split-26-ways-on-each-byte tree would probably work just as well.
The sorting-and-aggregating option: Run a traditional mergesort, but attach counters (initialized to 1) to each word; and every time you find yourself comparing two identical words, replace them by a single record with the sum of the counters.
Why drill a candidate for a technical writer position on hash functions and memory needs and speed and all that?
It seems to me like whichever company this was (I'm guessing Google) that the interviewer only knows how to ask one type of question, almost as if he/she was reading from a script.
People tend to forget that every interview is 2-way, not just 1-way.
If I was this candidate, I would have rejected this company and (possibly) sent them a nice form letter later that week.
I particularly like the jab at the interviewer for not having instant recall of every single CS algorithm. I keep TAOCP on my desk, and /because/ I don't know every single algorithm.
No, they're not asking for details of hash table implementation. The main goal is to see if you can scale the algorithm, for which they're the real experts. The hash table discussion is a mere diversion. The "expected" progression of the particular discussion is: 1. hash table implementation (simplest map container) when you have enough RAM to see if the candidate gets cs basics. 2. sort | uniq -c when you have enough disks on a single node to see if the candidate has experience with non-trivial amount of data (larger than RAM.) and understanding of modern disk performance characteristics (random vs sequential I/O) 3. map-reduce on multiple nodes for the entire internet; see if the candiate has experience and understandings with distributed computing. So the author didn't make very far. His attitude and mindset were also getting in the way of interviewers' steering the interview. It's a classic case of impedance mismatch in interviews.
While I like to hire people smarter than I am, I rather like to draw that conclusion myself, rather than have somebody try to wrestle me to the ground to prove it.
I'd hire him in a heartbeat.
But it depends on the job :)
Perhaps you could enlighten me?
(1) Use Zipf's law (or a more suitable distribution) to identify how many times we expect the 10,000th word to occur in a random distribution of documents. That gives us the maximum interval at which the 10,000th word will repeat itself at any level of statistical confidence.
(2) Don't count every word. Only track the top 10,000 words plus a tail of whatever size is necessary to capture this maximum interval. With Zipf's law this means less than 20,000 words. The exact number can be calculated easily enough.
(3) Store words in a data structure that provides fast access by alphabetical search (tree) and also by frequency of occurrence (list). Bump words up the list as we run into them. When you run into a word that isn't in your tree, grab the entry at the bottom of the frequency list and re-insert it as your new word by repositioning. There is no need to traverse much data
(4) Lower frequency content will naturally drop off the list. Higher frequency content will naturally move up. And we've structured our program so that we can make statistical inferences about the words that are left....
(5) Remember to normalize incoming data with a Porter-Stemmer algorithm or something. Lots of small details like that, but it is really just icing on the cake.
Result? You get a statistically significant test you can run multiple times at whatever level of accuracy you desire. The software doesn't require huge computational muscle power or massive amounts of memory, since we throw out the long tail of statistically irrelevant content on an ongoing basis. That coupled with our elegant data structure - we're mostly swapping pointers - keeps the software small and fast.
Is there a better approach?
I think I might inject this kind of thing into an interview just to weed out the people unwilling to stand up to insanity. If you can't tell me when I'm going too far down the wrong path, how can I be sure you'll know if you're doing the same thing?
At the end of the day he petulantly (his words) stuck to a point that could have been made in a simple sentence (well, assuming we agree there is no way this could work in the real world because of the fluidity of language and the poor behaviour of web crwlers then I would.....). If the interviewer is looking for a discussion on that he will pick up and ask for more. If not he will let it pass (and probably note that your recognised the issue).
In an interview you must dangle relevant information in front of the interviewer and wait for him to pounce on things he wants more information on :)
Also: NEVER assume a concept the interviewer has "never heard" of IS something he/she has never heard of. That is a simple mistake to fall into.
Of course, they just want you to explain the concept as if they've never heard of it. However, he was writing this after-the-fact, so I'm assuming it still seemed that he hadn't heard of the concept in retrospect, which is a much different beast.
That said, it was quite obvious that guy was trying to avoid the question. That wouldn't have sat well with me.
I didn't give nearly as much pushback as the author, though, since I assumed that wasn't the point.
Just use sort and uniq.
Or if it's slow, sort in parallel, then merge into one stream, and extract the frequencies.
Maybe this is why most technical documentation sucks, particyularly helppages oriented towards end-users.
Both Yahoo and Google offer services interesting to programmers; presumably they want documentation of a similar quality.
The interviewer was priming for this particular answer: Keep the buckets in a linked list. Each time you increment a bucket, move it to the front of the list. When you're counting frequencies, this approach will mean that the most frequently occurring keys will be closer to the front of the list.
I know this because I was asked a similar question in an interview with a certain well-known PC software company. I didn't know the answer either, but still got an offer.
Either you love it and want to hire the guy in a moment, or you think he's an unbearable smartass.
Interview != Quiz
Most interviewers are NOT aware of this.(at least the stereotypical "interview" at the stereotypical tech company. Then again, I think Wall Street/financial firms probably do the same. exact. thing.)
Edit: I would actually like to know if/why the method used is more useful than the one I gave. I'm not just trying to be arrogant.
If you have a hash space large enough to hold the longest English word converted to base 26, then you might still need to be concerned with clustering properties. It's considered undesirable to have large stretches within the hash space with no associated key; my understanding is that this somehow impairs the distribution from the modulus step in most hashtable implementations.
Converting a word into base 26 will give you a huge number. Over six or seven characters and your hash does not fit into a 32-bit integer, and over 13 characters it will not fit into a 64-bit word.
So he chooses to multiply by number that is prime in relation to the table size because that would definitely avoid cycles (say, if you've got a table of size 16 and double the number each time there are many positions into which words with that prefix will never hash, which can be a very bad idea).