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
- 1 ≤ w.length ≤ 10⁴
- 1 ≤ w[i] ≤ 10⁵
- pickIndex is called at most 10⁴ times
- Here a seed fixes the random draws so runs repeat
Edge cases to test
- One weight
- Very large total weight
- Zero-weight entries never picked (if allowed)
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 loC++
#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
- Plus One (Easy)
- Happy Number (Easy)
- GCD and LCM (Euclid) (Easy)
- Count Primes (Sieve of Eratosthenes) (Medium)
- Pow(x, n) (Medium)
- Count Good Numbers (mod 1e9+7) (Medium)
- Multiply Strings (Medium)
- Reverse Integer (Medium)
- String to Integer (atoi) (Medium)
- Detect Squares (Medium)
- Shuffle an Array (Medium)
- Linked List Random Node (Medium)
- Pascal's Triangle (Easy)
- nCr mod p (Medium)
- Max Points on a Line (Hard)