Algo-Sim › Math & Geometry

Random Pick with Weight

Medium · Math & Geometry · step through it in Java, Python and C++ on your own input

Pick index i with probability w[i] / sum(w): a uniform target in 1..total, then binary search the prefix sums for its owner.

Problem

You are given positive weights w. Implement pickIndex(), which returns an index in [0, w.length − 1] at random, where index i is chosen with probability w[i] / sum(w).

Constraints

Edge cases to test

Follow-up questions

What if weights change between picks?
Keep the prefix sums in a Fenwick tree: O(log n) per update and per pick.
Can a pick be O(1)?
The alias method preprocesses in O(n) and samples in O(1).

Solution

Java

class Solution {
    private final int[] prefix;
    private final Random rand = new Random();

    public Solution(int[] w) {
        prefix = new int[w.length];
        for (int i = 0, total = 0; i < w.length; i++)
            prefix[i] = total += w[i];
    }

    public int pickIndex() {
        // A uniform target in 1..total; index i owns w[i] of those values.
        int target = rand.nextInt(prefix[prefix.length - 1]) + 1;
        int lo = 0, hi = prefix.length - 1;
        while (lo < hi) {
            int mid = (lo + hi) / 2;
            if (prefix[mid] < target) lo = mid + 1;
            else hi = mid;
        }
        return lo;
    }
}

Python

import random


class Solution:
    def __init__(self, w):
        self.prefix, total = [], 0
        for x in w:
            total += x
            self.prefix.append(total)

    def pickIndex(self):
        # A uniform target in 1..total; index i owns w[i] of those values.
        target = random.randint(1, self.prefix[-1])
        lo, hi = 0, len(self.prefix) - 1
        while lo < hi:
            mid = (lo + hi) // 2
            if self.prefix[mid] < target:
                lo = mid + 1
            else:
                hi = mid
        return lo

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
    vector<int> prefix;

  public:
    Solution(vector<int> &w) {
        for (int i = 0, total = 0; i < int(w.size()); i++)
            prefix.push_back(total += w[i]);
    }

    int pickIndex() {
        // A uniform target in 1..total; index i owns w[i] of those values.
        int target = rand() % prefix.back() + 1;
        int lo = 0, hi = int(prefix.size()) - 1;
        while (lo < hi) {
            int mid = (lo + hi) / 2;
            if (prefix[mid] < target) lo = mid + 1;
            else hi = mid;
        }
        return lo;
    }
};

More Math & Geometry problems