KatInterview

912. Random Pick with Weight

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Prefix Sums with Binary Search

This problem asks us to perform a weighted random pick. An index with a higher weight should have a higher probability of being chosen. We can solve this by mapping the weights to intervals on a number line and then using a uniform random number to pick a point on that line. The interval containing the point corresponds to the chosen index.

Solution

Random Pick with Weight in Python

import random
import itertools
import bisect

class Solution:

    def __init__(self, w: List[int]):
        # Calculate prefix sums. `itertools.accumulate` is a clean way to do this.
        # e.g., w = [1, 3, 2] -> prefix_sums = [1, 4, 6]
        self.prefix_sums = list(itertools.accumulate(w))
        # The total sum is the last element of the prefix sums array.
        self.total_sum = self.prefix_sums[-1]
        
    def pickIndex(self) -> int:
        # Generate a random integer from 1 to total_sum (inclusive).
        target = random.randint(1, self.total_sum)
        
        # Use binary search to find the insertion point for the target.
        # `bisect.bisect_left` finds the first index `i` in `prefix_sums`
        # where `prefix_sums[i]` is not less than `target` (i.e., >= target).
        # This is exactly the logic we need.
        # For example, if prefix_sums = [1, 4, 6] and target = 3,
        # bisect_left will return index 1, because prefix_sums[1] (4) >= 3.
        return bisect.bisect_left(self.prefix_sums, target)


# Your Solution object will be instantiated and called as such:
# obj = Solution(w)
# param_1 = obj.pickIndex()

Random Pick with Weight in Java

class Solution {
    private int[] prefixSums;
    private int totalSum;
    private Random rand;

    public Solution(int[] w) {
        this.prefixSums = new int[w.length];
        this.totalSum = 0;
        this.rand = new Random();

        // Calculate prefix sums
        for (int i = 0; i < w.length; ++i) {
            totalSum += w[i];
            prefixSums[i] = totalSum;
        }
    }
    
    public int pickIndex() {
        // Generate a random target number between 1 and totalSum (inclusive).
        // rand.nextInt(totalSum) generates a number in [0, totalSum - 1].
        // Adding 1 shifts the range to [1, totalSum].
        int target = rand.nextInt(totalSum) + 1;

        // Perform binary search to find the index.
        // We are looking for the smallest index `i` such that prefixSums[i] >= target.
        int low = 0;
        int high = prefixSums.length - 1;
        
        while (low < high) {
            int mid = low + (high - low) / 2;
            if (prefixSums[mid] < target) {
                low = mid + 1;
            } else {
                // prefixSums[mid] >= target, so mid could be the answer.
                // We search in the left half including mid.
                high = mid;
            }
        }
        
        // `low` will be the first index where prefixSums[low] >= target.
        return low;
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(w);
 * int param_1 = obj.pickIndex();
 */

Random Pick with Weight in C++

class Solution {
private:
    std::vector<int> prefix_sums;
    // Modern C++ random number generation
    std::mt19937 generator;
    std::uniform_int_distribution<int> distribution;
    int total_sum = 0;

public:
    Solution(vector<int>& w) {
        // Seed the random number generator
        // std::random_device is a true non-deterministic random number generator (if available)
        std::random_device rd;
        generator.seed(rd());

        int current_sum = 0;
        for (int weight : w) {
            current_sum += weight;
            prefix_sums.push_back(current_sum);
        }
        total_sum = current_sum;

        // Set up the uniform distribution for the range [1, total_sum]
        if (total_sum > 0) {
            distribution = std::uniform_int_distribution<int>(1, total_sum);
        }
    }
    
    int pickIndex() {
        // Generate a random number in the range [1, total_sum]
        int target = distribution(generator);

        // Use binary search (std::lower_bound) to find the first prefix sum
        // that is greater than or equal to the target.
        // The iterator returned by lower_bound points to this element.
        auto it = std::lower_bound(prefix_sums.begin(), prefix_sums.end(), target);

        // The index is the distance from the beginning of the vector to this iterator.
        return std::distance(prefix_sums.begin(), it);
    }
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution* obj = new Solution(w);
 * int param_1 = obj->pickIndex();
 */

Random Pick with Weight in TypeScript

class Solution {
    private prefixSums: number[];
    private totalSum: number;

    constructor(w: number[]) {
        this.prefixSums = [];
        this.totalSum = 0;

        // Calculate prefix sums
        for (const weight of w) {
            this.totalSum += weight;
            this.prefixSums.push(this.totalSum);
        }
    }

    pickIndex(): number {
        // Generate a random number between 0 (inclusive) and totalSum (exclusive).
        const randomNum = Math.random() * this.totalSum;

        // Perform binary search to find the index.
        // We are looking for the smallest index `i` such that prefixSums[i] > randomNum.
        let low = 0;
        let high = this.prefixSums.length - 1;

        while (low < high) {
            // Use Math.floor to get an integer mid-point
            const mid = Math.floor(low + (high - low) / 2);
            if (this.prefixSums[mid] <= randomNum) {
                low = mid + 1;
            } else {
                // this.prefixSums[mid] > randomNum, so mid could be the answer.
                // We search in the left half including mid.
                high = mid;
            }
        }

        // `low` will be the first index where prefixSums[low] > randomNum.
        return low;
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * var obj = new Solution(w)
 * var param_1 = obj.pickIndex()
 */

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.