Recently I was offered to solve the following task (with C++).
Write a function which retrieves M distinct random values from N values.
Prerequisites:
- the input array of N values is not necessarily sorted;
- the input array of N values may contain duplicates.
The thing which made me ask for a solution is that I was said that it is possible to implement the algorithm which would have complexity O(M). To me this sounds insane and I haven't managed to find anything at least close to O(M).
Is it even possible to write the algorithm with such small complexity? If no, what complexity can I achieve at all? I would also like to see examples (not necessarily with C++).