KatInterview

Weighted Random Item Picker from Scratch

Arrays & HashingModel answer
EasyModel answerArrays & Hashingprobabilityprefix-sumbinary-search

Last updated

Implement a function that draws one item from a list at random, where each item's selection probability is proportional to its given weight.

Weighted Random Item Picker

You need to implement the following function without using any library that does the weighted sampling for you (no numpy, no random.choices):

def weighted_sample(items, weights=None):
    # returns a single element from items
    pass

What It Should Do

Given a list of items and a corresponding list of weights, return one item such that item i is chosen with probability proportional to weights[i]. In other words, if the weights are [1, 4, 5], the third item should come up roughly 50% of the time, the second 40%, and the first 10%.

Weights do not need to sum to 1 — your implementation must normalize internally.

Parameters

  • items: a list of any objects, length 1 to 10^5.
  • weights: a list of non-negative finite numbers, same length as items. If None, treat all items as equally likely.

Error Conditions

Raise ValueError when:

  • items is empty.
  • weights is provided but its length differs from items.
  • Any weight is negative or non-finite (NaN, infinity).
  • All weights are zero (no valid distribution exists).

Randomness

Use only random.random(), which returns a float uniformly distributed over [0.0, 1.0).

Examples

items   = ['A', 'B', 'C']
weights = [1, 4, 5]
# Expected long-run frequencies: A→10%, B→40%, C→50%

items   = ['Red', 'Blue']
weights = [0.5, 0.5]
# Each item picked ~50% of the time

items   = ['X', 'Y', 'Z']
weights = [0, 3, 0]
# Only 'Y' is ever returned

What Is Expected

  • A correct implementation that satisfies the probability requirement.
  • Proper input validation with ValueError and a clear message.
  • A brief explanation of your approach, its correctness, and its time/space complexity.
  • Discussion of edge cases and how you handle them.
  • An answer to the follow-up: how would you redesign this for drawing thousands of samples from the same fixed distribution?

Hints

Hint 1

Lay the weights end-to-end on a number line from 0 to their total. Each item owns a segment proportional to its weight. What does it mean to 'pick a random point' on that line?

Hint 2

Once you have prefix sums, you need to find which segment a random value falls into. A binary search on the prefix array does this in O(log n) — think carefully about whether to use bisect_left or bisect_right and why the choice matters at exact boundary values.

Hint 3

You don't need to divide every weight by the total to normalize. Instead, scale your random draw up to [0, total) and search the un-normalized prefix array directly. This saves n divisions and avoids a separate accumulation of rounding error.