Given an array and a value k, write a function to return index of element that equals to k with the probability of k/sum(input array). Assume there is no duplicate number in input array.
For example, if the input array is 1,4,2,3. The function should have the following behavior:
return 0 with probability 1/10;
return 1 with probability 4/10;
return 2 with probability 2/10;
return 3 with probability 3/10;
Question 2: How to deal with it if there are duplicates in the array?
I was thinking binary search is good to find an element in array, however I haven't figured out how to connect it with the probability.
Edited: As suggested, this question is similar to my question. However, its solution was not what I expected. I was looking for a solution that is embedded with binary search, which potentially decreases time complexity.
A good solution about given a key, how to use binary search to find the first element bigger than key in sorted array.