09 · Math & Number Theory

#528 Random Pick with Weight

Mediumsolve on LeetCode ↗

frequently reported atMetaUberLinkedInAmazonGoogle

the problem

In plain words

You get positive weights w[0..n−1]. Build a class whose pickIndex() returns a random index, where index i comes up with probability w[i] / (sum of all weights). The judge checks that every pick is a valid index and that, over many picks, each index's share is close to its weight's share.

in w = [1]; pickIndex()

out 0

There is only one index.

in w = [1, 3]; pickIndex() × 5

out e.g. [1, 1, 1, 1, 0]

Index 1 should come up about 75% of the time; any sequence with that tendency is accepted.

  • 1 ≤ w.length ≤ 10⁴
  • 1 ≤ w[i] ≤ 10⁵
  • pickIndex is called at most 10⁴ times

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

Design: implement every operation. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #303
    2. #35
      Search Insert Position
      Easyin Binary Search