Possible Duplicate:
Algorithm to select a single, random combination of values?
This is an interview question i've seen online.
You have one billion numbers, implement getRandom() which returns a random number from them.
Constaints: 1. No duplicate returning value. 2. getRandom() will at most be invoked 100 million times. Then optimize for space.
How is this solution, and what are some better ones?:
Shuffle the array of numbers. Keep a counter starting at 0. Everytime the user calls getRandom, return the value at counter index. Increment the counter.