Find random number not in array – Code

Find random number not in array is a tricky question. It is pretty straight forward to find a random element in array by getting an random index within the range. If you are asked to find a random element that is NOT in array, your brain might not response quickly as you wish. There is a strategy to solve this kind of question. You just need to think about “negative space”.

There are two steps to solve this kind of “not in” question. First find the complement of the elements. For example, given an array of 5 element, if you have {1,2}, the complement elements are { 3, 4,5}. The second step is simply to find a random number from {3, 4, 5}.

Google Interview Question:
find random number 0,M, that’s not in the array K,
int uniform(int M); -> 0, …, M-1 this function return a random # between 0, M-1

Java Code:

Input array: [1, 3, 4, 6, 9]
Random number not in the array: 7

O Notation:
Time complexity: O(n+k), n is the range of the random number, m in the number of elements in K
Space complexity: O(n)

If you have any questions or want to put comments, please post at youtube. I will answer you!
The code displayed here is the simplified version after the enhancement in the 2nd edition of Java coding interview pocket book. Please click the top download button to download the original version.

Find random number not in array (YouTube)
The complete list of coding interview questions

Comments are closed