BackendML

Weighted Random Selection

Medium2 min read
Weighted Random SelectionThe Weighted Random Selection problem requires randomly selecting an index where each index has a probability proportional to its assigned weight.

Problem

Given an integer array w, where w[i] represents the weight of index i, randomly select an index such that the probability of selecting an index is proportional to its weight.

For example, if w = [1,3], index 0 should be selected with probability 1/4, while index 1 should be selected with probability 3/4.

Example(s)

Example 1

Input
w = [1,3]
Output
0 or 1
Explanation
Index 0 has a probability of 1/4, while index 1 has a probability of 3/4.

Example 2

Input
w = [2,5,3]
Output
0, 1, or 2
Explanation
The total weight is 10. Therefore, index 0 has probability 2/10, index 1 has probability 5/10, and index 2 has probability 3/10.

Solution

This solution uses a Prefix Sum array and Binary Search.

We first convert the weights into cumulative sums. For example, if w = [1,3,2], the prefix sum becomes [1,4,6]. The total weight is 6, so we randomly generate a number between 1 and 6.

Each index owns a range of numbers based on its weight. For [1,3,2], index 0 owns [1], index 1 owns [2,4], and index 2 owns [5,6]. Therefore, selecting a random number from 1 to 6 gives each index a probability proportional to its weight.

We then use Binary Search to find the first prefix sum that is greater than or equal to the randomly generated value.
class Solution {

    private final int[] prefix;
    private final Random random;

    public Solution(int[] w) {
        prefix = new int[w.length];
        random = new Random();

        prefix[0] = w[0];

        for (int i = 1; i < w.length; i++) {
            prefix[i] = prefix[i - 1] + w[i];
        }
    }

    public int pickIndex() {
        int target = random.nextInt(prefix[prefix.length - 1]) + 1;

        int left = 0;
        int right = prefix.length - 1;

        while (left < right) {
            int mid = left + (right - left) / 2;

            if (prefix[mid] >= target) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return left;
    }
}

Complexity

Building the prefix sum array takes O(n) time. Each pickIndex() operation uses Binary Search, taking O(log n) time.

The prefix sum array requires O(n) extra space.

Comments

No comments yet. Ask a question or share what helped.