Random Set
17.3 Random Set: Write a method to randomly generate a set of m integers from an array of size n. Each element must have equal probability of being chosen.
The Idea: First lets think of some possible approaches. If n = m, then it is just a shuffle and returning the shuffled array of elements. Otherwise if m < n, we can return [0-m] needed elements from this array. This would be O(N) time, but highly wasteful if we wanted to chose 1 element from an array of size 1 million.
Instead what we could do is randomly generate an index between [0 - N]
, append this number to the result array, and then swap the last element with this chosen index in the array. Then our range of next possible elements to chosen from becomes [0-(N-1)]
. For the next element, repeat the same process as between, but now swap with N-2
, and so fourth.
Complexity: O(n) time where n is the number of elements to generate. O(1) extra space
Last updated