Skip to contentKEEP THE CRAFTTHE SANCTUARY

Resolve a Weighted Random Pick

Turn a random draw into an index, where each index is picked in proportion to its weight.

The problem

Implement Solution.pickIndex(weights, draw). In Random Pick with Weight, index i is chosen with probability weights[i] / sum(weights). Here the random number is passed in so the answer is predictable: draw is an integer from 1 to sum(weights). Index 0 owns the first weights[0] draws, index 1 owns the next weights[1] draws, and so on. Return the index that owns draw. For example, with weights [1, 3, 2], index 0 owns draw 1, index 1 owns draws 2 to 4, and index 2 owns draws 5 and 6, so draw 4 returns 1. Every weight is a positive integer, 1 <= len(weights) <= 10000, and sum(weights) <= 1000000000.

Starter code

class Solution:
    def pickIndex(self, weights, draw):
        pass

Public examples

  1. weights = [1, 3, 2], draw = 4gives1
  2. weights = [9], draw = 9gives0
  3. weights = [2, 5, 1], draw = 2gives0

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.