</>

528. Random Pick with Weight

Medium
Binary Search Time O(N) Space O(N)
↗ Open on LeetCode Source: Misc

Quick review

Pattern
Binary Search
Time
O(N)
Space
O(N)

Standard Solution (C++)

SummaryGiven an array of positive integer weights, implement a picker that randomly selects an index such that each index is chosen with probability proportional to its weight.

Approach
  • Build a prefix-sum array once in the constructor so that each index i owns the half-open interval [prefixSum[i-1], prefixSum[i]) on the number line [0, total).
  • On each pickIndex() call, draw a random integer target in [0, total) via rand() % prefix.back() and use upper_bound to locate the first prefix-sum entry strictly greater than target — that entry's index is the answer.
  • This works because target falls in [prefixSum[i-1], prefixSum[i]-1] for some i, and upper_bound returns a pointer to prefixSum[i] (the first element strictly greater), yielding index i directly.
#include <vector>
#include <numeric>
#include <algorithm>
#include <cstdlib>
using namespace std;

class Solution {
    vector<int> prefix; // prefix[i] = sum of w[0..i]
public:
    // O(n) — build cumulative weight array once
    Solution(vector<int>& w) {
        prefix.resize(w.size());
        partial_sum(w.begin(), w.end(), prefix.begin());
    }

    // O(log n) — binary-search for the interval that contains the random target
    int pickIndex() {
        // Draw uniformly from [0, total)
        int target = rand() % prefix.back();
        // upper_bound finds first prefix entry > target, which is exactly
        // the index whose weight-interval contains target.
        return static_cast<int>(
            upper_bound(prefix.begin(), prefix.end(), target) - prefix.begin()
        );
    }
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution* obj = new Solution(w);
 * int param_1 = obj->pickIndex();
 */
Time O(n) constructor, O(log n) per pickIndex() Space O(n)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

#include <vector>
#include <algorithm>
using namespace std;

class Solution {
    vector<int> prefixSum;
public:
    Solution(vector<int>& w) {
        prefixSum.resize(w.size());
        prefixSum[0]=w[0];
        for(int i=1; i<w.size(); ++i){
            prefixSum[i]=prefixSum[i-1]+w[i];
        }
    }
    
    int pickIndex() {
        int target=rand()%prefixSum.back();
        auto it=std::upper_bound(prefixSum.begin(), prefixSum.end(), target);
        return distance(prefixSum.begin(), it);
    }
};

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

// Time Complexity: O(N) for constructor, O(logN) for pickIndex() where N is the size of the input vector w.
// Space Complexity: O(N) for storing the prefix sum array.
Time O(N) Space O(N)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground C++

Your solution. A driver couldn't be auto-generated for this signature — add a main() that calls the method and prints the result, then Run.

C++ ▶ Runnable Couldn't auto-generate a driver for this signature — edit to add one.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern