AlgoMaster Logo

Random Pick with Weight

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Prefix Sum + Binary Search Approach

Intuition:

The main goal is to pick an index i with a probability proportional to w[i]. If we imagine each weight as a segment on a line of length sum(weights), then we can pick a random point on this line and determine which segment it falls into using binary search. Thus, the problem boils down to constructing a prefix sum array and using binary search to determine our pick.

  1. Compute prefix sums of the weights. This helps in cumulatively understanding the "length" of each segment.
  2. Use random function to pick a target in the range of 0 to the total sum of weights.
  3. Use binary search to find the index where the target falls in the prefix sum array.

Code:

2. Binary Search Tree Approach (Optimal)

Intuition:

This approach uses a dynamic data structure like a balanced binary search tree (e.g., TreeMap in Java) to store cumulative weights, allowing for efficient cumulative lookup and random access. This is especially efficient if weights frequently update or if the number of weights (N) is very large.

  1. Store cumulative weights in a TreeMap, where each key is a cumulative weight, and the value is the corresponding index.
  2. For each pickIndex call, randomly determine a target and find the smallest key in the map greater or equal to the target.

Code: