bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 528. Random Pick with Weight

528. Random Pick with Weight

Leetcode Solutions

Prefix Sums with Binary Search

  1. Calculate the prefix sum array from the input weights.
  2. Store the total sum of weights for scaling the random number.
  3. When pickIndex() is called, generate a random number between 0 and 1, then scale it by the total sum to get the target offset.
  4. Perform a binary search on the prefix sum array to find the first prefix sum that is larger than the target offset.
  5. Return the index of this prefix sum as the result of pickIndex().
UML Thumbnail

Prefix Sums with Linear Search

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...
bugfree Icon
OR