Leetcode 528: Random Pick with Weight

grid47
grid47
Exploring patterns and algorithms
Sep 15, 2024 7 min read

A series of objects with different weights, each object softly glowing based on its probability of being picked.
Solution to LeetCode 528: Random Pick with Weight Problem

You are given a 0-indexed array of positive integers w, where w[i] describes the weight of the ith index. You need to implement the function pickIndex() which randomly picks an index in the range [0, w.length - 1] (inclusive), and the probability of picking index i is w[i] / sum(w).
Problem
Approach
Steps
Complexity
Input: The input consists of an array w where each element represents a positive weight.
Example: [2, 5]
Constraints:
• 1 <= w.length <= 10^4
• 1 <= w[i] <= 10^5
Output: Return a randomly selected index i, where the probability of selecting i is proportional to its weight w[i].
Example: 1
Constraints:
• The result should be a valid index between 0 and w.length - 1.
Goal: The goal is to implement pickIndex() in such a way that the probability of selecting each index is proportional to its weight.
Steps:
• 1. Precompute the cumulative sum of weights in the array.
• 2. Use a random number generator to pick a number in the range of 1 to the total sum of weights.
• 3. Use binary search to find the corresponding index based on the generated random number.
Goal: The problem needs to handle an array with a length up to 10^4 efficiently.
Steps:
• 1 <= w.length <= 10^4
• 1 <= w[i] <= 10^5
Assumptions:
• The array w contains positive integers representing the weight of each index.
Input: [2, 5]
Explanation: The total weight is 7, so the probability of picking index 0 is 2/7 and index 1 is 5/7.

Input: [1]
Explanation: With only one element in the array, the only valid index is 0, so the result is always 0.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus