LeetCode 528: Random Pick with Weight Solution
Master LeetCode problem 528 (Random Pick with Weight), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
528. Random Pick with Weight
Problem Explanation
Explanation
To solve this problem, we need to generate a random index based on the weights provided in the input array. We can achieve this by creating a prefix sum array to store the cumulative sum of weights. We then generate a random number between 1 and the total sum of weights, and find the index where this random number falls in the prefix sum array.
Solution Code
import java.util.Random;
class Solution {
int[] prefixSum;
Random rand;
public Solution(int[] w) {
prefixSum = new int[w.length];
rand = new Random();
prefixSum[0] = w[0];
for (int i = 1; i < w.length; i++) {
prefixSum[i] = prefixSum[i - 1] + w[i];
}
}
public int pickIndex() {
int totalSum = prefixSum[prefixSum.length - 1];
int randNum = rand.nextInt(totalSum) + 1;
int left = 0, right = prefixSum.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (prefixSum[mid] < randNum) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 528 (Random Pick with Weight)?
This page provides optimized solutions for LeetCode problem 528 (Random Pick with Weight) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 528 (Random Pick with Weight)?
The time complexity for LeetCode 528 (Random Pick with Weight) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 528 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 528 in Java, C++, or Python.