Search⌘ K
AI Features

Solution: Random Pick with Weight

Explore how to implement a weighted random picker by transforming weights into running sums and using a modified binary search. This method helps you select indexes with probabilities proportional to their weights efficiently. Understand the tradeoffs between naive linear search and optimized binary search approaches to improve algorithm performance in coding interviews.

Statement

You’re given an array of positive integers, weights, where weights[i] is the weight of the ithi^{th} index.

Write a function, Pick Index(), which performs weighted random selection to return an index from the weights array. The larger the value of weights[i], the heavier the weight is, and the higher the chances of its index being picked.

Suppose that the array consists of the weights [12,84,35][12, 84, 35]. In this case, the probabilities of picking the indexes will be as follows:

  • Index 0: 12/(12+84+35)=9.2%12/(12 + 84 + 35) = 9.2\%

  • Index 1: 84/(12 ...