Given the array and the value of k, write a function that returns the index of the element, which is equal to k with probability k / sum (input array). Suppose there is no duplicate number in the input array.
For example, if the input array is 1,4,2,3. The function should have the following behavior:
returns 0 with a probability of 1/10;
return 1 with a probability of 4/10;
return 2 with a probability of 2/10;
return 3 with a probability of 3/10;
Question 2: How to deal with this if there are duplicates in the array?
I thought binary search was good to find an element in an array, however I did not understand how to relate it to probability.
Edited : As suggested, this question is similar to my question. However, his decision was not what I expected. I was looking for a solution that has binary search built in , which potentially reduces the time complexity.
A good decision on a given key is how to use binary search to find the first element that is larger than the key in a sorted array.
source
share