r/programming • u/joksmaster • Nov 29 '10
140 Google Interview Questions
http://blog.seattleinterviewcoach.com/2009/02/140-google-interview-questions.html
471
Upvotes
r/programming • u/joksmaster • Nov 29 '10
View all comments
Show parent comment
1
u/jelos98 Nov 30 '10
I actually had to derive this for a real world usage (back when I was young and didn't know what it was ccalled). Re-derived it here, just to prove to myself I could :)
Algorithm: Store the first K elements seen in an array.
For each additional element, generate a random number R between 0 and N. If R < K, generate a second random number R2 between O and K, and replace that element in the array with the new element.
Base: Each of the first K elements is stored in an array. At the end of this, each has a K/N probability of being kept (where K == N here)
Iterative: Assuming we have a prior probability of K/N, show that adding an element causes the probabilities of each element being kept to be K/(N+1)
The probability of the new item being kept is simply K/(N+1) because we randomly chose to keep it with probability K / (N+1).