Random Pick With Weight solution explained

Random Pick With Weight asks you to return index i with probability equal to its weight divided by the total of all weights. Build the running totals of the weights once, draw a random integer from 1 to the total, and binary-search for the first running total that reaches it. Setup is O(n) and each pick is O(log n), using O(n) extra space.

By Published 7 min read

The task, restated

You are given a list of positive whole-number weights. Write a class whose pick_index() method returns an index at random, where index i comes up with probability w[i] divided by the sum of all weights. The constructor runs once and pick_index() is called many times, so the per-pick cost matters more than setup. You may use your language's uniform random number generator.

Examples made up for this page
WeightsProbabilitiesRunning totalsDraws (1 to total) that map to each index
[2, 5, 3]0.2, 0.5, 0.3[2, 7, 10]1-2 to index 0, 3-7 to index 1, 8-10 to index 2
[1, 1, 1, 1]0.25 each[1, 2, 3, 4]each draw maps to its own index
[9]1.0[9]every draw maps to index 0
[1, 98, 1]0.01, 0.98, 0.01[1, 99, 100]1 to 0, 2-99 to 1, 100 to 2
Examples made up for this page. Scroll sideways on a small screen.

Things to confirm: are weights integers or can they be fractional? Can a weight be 0, and if so should that index ever be picked? Is the list fixed, or will weights change between picks? The last question changes the data structure, as the follow-ups below show.

Where it shows up

Weighted sampling is everywhere in real systems: load balancers that send more traffic to bigger servers, A/B test allocation, ad rotation, game loot tables and sampling in machine learning. In interviews it is a short problem that tests two things at once, whether you can turn a probability question into a search over prefix sums, and whether you can get binary search boundaries exactly right. Typical follow-ups:

  • Weights are floating point. Draw a float in [0, total) and find the first running total strictly greater than the draw.
  • Weights change between picks. A Fenwick tree (binary indexed tree) supports updating one weight and searching the prefix sums in O(log n) each.
  • Picks must be O(1). The alias method precomputes a table in O(n) so each pick needs one uniform index and one coin flip.
  • Pick k distinct indexes without replacement. Draw, then remove that weight, which again points to a Fenwick tree, or use a weighted reservoir sampling scheme.

Two simple but weak designs

The first idea is a bag: repeat each index as many times as its weight and pick a uniform element. Picks are O(1), but the bag has sum(w) entries, which is hopeless when weights are in the millions. The second idea keeps the running totals and scans them from the left on each pick, stopping at the first total that reaches the draw. Memory is O(n), but each pick costs O(n). The scan is a good reference for testing the fast version, because both must map every draw to the same index.

import random

class ScanPicker:
    def __init__(self, weights):
        self.totals = []
        running = 0
        for w in weights:
            running += w
            self.totals.append(running)

    def index_for(self, target):
        for i, upto in enumerate(self.totals):
            if upto >= target:
                return i

    def pick_index(self):
        return self.index_for(random.randint(1, self.totals[-1]))
Python: running totals with a linear scan per pick.

Lay the weights end to end on a number line of length total. Index i owns the integers from prefix[i - 1] + 1 to prefix[i]. A uniform integer draw from 1 to total lands in index i's stretch with probability w[i] / total, which is exactly what is required. Because the running totals only increase, finding the stretch is a binary search for the first prefix value that is at least the draw, which Python's bisect_left provides directly.

import random
from bisect import bisect_left

class WeightedPicker:
    def __init__(self, weights):
        self.prefix = []
        running = 0
        for w in weights:
            running += w
            self.prefix.append(running)
        self.total = running

    def index_for(self, target):
        # target is a whole number from 1 to total
        return bisect_left(self.prefix, target)

    def pick_index(self):
        return self.index_for(random.randint(1, self.total))
Python: bisect_left over the running totals.
class WeightedPicker {
  constructor(weights) {
    this.prefix = [];
    let running = 0;
    for (const w of weights) {
      running += w;
      this.prefix.push(running);
    }
    this.total = running;
  }

  indexFor(target) {
    let lo = 0;
    let hi = this.prefix.length - 1;
    while (lo < hi) {
      const mid = (lo + hi) >> 1;
      if (this.prefix[mid] >= target) hi = mid;
      else lo = mid + 1;
    }
    return lo;
  }

  pickIndex() {
    return this.indexFor(Math.floor(Math.random() * this.total) + 1);
  }
}
JavaScript: the same split between a deterministic search and a random draw.

Splitting the search from the draw is deliberate. index_for has no randomness, so you can test it on every possible draw and prove the mapping is right, and only pick_index touches the generator. Interviewers notice when a candidate designs for testability without being asked.

Getting the boundaries right

Draws from 1 to total pair with the first prefix that is at least the draw (bisect_left). Draws from 0 to total - 1 pair with the first prefix that is strictly greater than the draw (bisect_right). Mixing the two is the classic bug. With weights [2, 5, 3], drawing from 0 to 9 and using bisect_left sends draw 0 to index 0 and draw 2 to index 0 too, so index 0 receives three of the ten draws instead of two. Pick one convention and say it out loud before writing the search.

Weights [2, 5, 3], prefix [2, 7, 10]
DrawFirst prefix at least the drawIndex
120
220
371
771
8102
10102
Weights [2, 5, 3], prefix [2, 7, 10]. Scroll sideways on a small screen.

Time and space

n weights, W their sum
DesignSetupPer pickExtra space
Bag with each index repeatedO(W)O(1)O(W)
Running totals, linear scanO(n)O(n)O(n)
Running totals, binary searchO(n)O(log n)O(n)
Alias method (follow-up)O(n)O(1)O(n)
Fenwick tree with updates (follow-up)O(n)O(log n), updates O(log n)O(n)
n weights, W their sum. Scroll sideways on a small screen.

Edge cases

  • A single weight: every pick returns 0.
  • Equal weights: the picker becomes a uniform choice, which is a quick sanity check.
  • Weights of 0, if allowed: they create zero-length stretches, and a lower-bound search on 1 to total skips them, because a prefix equal to the previous one is never the first to reach a draw.
  • Very large totals: fine in Python; in JavaScript, keep the total below 2 to the 53rd power so the draw stays exact.
  • Very skewed weights such as [1, 1000000]: correct with prefix sums, and exactly the case where the bag design fails on memory.

Mistakes to avoid

  • Drawing from 0 to total inclusive, which has total + 1 outcomes and skews every probability.
  • Pairing a 0-based draw with a lower-bound search, or a 1-based draw with an upper-bound search.
  • Recomputing the prefix sums inside pick_index, which turns every pick into O(n).
  • Testing only by sampling a few hundred picks and eyeballing the counts. Test the deterministic mapping on every draw, then sample many picks to confirm the generator is wired in.
  • Picking with a float draw and integer weights without thinking about the boundary at exactly a prefix value.

How to explain it out loud

Fictional example

From probability to binary search
Candidate
If I line the weights up end to end, each index owns a stretch as long as its weight, so a uniform draw over the whole length picks indexes with the right odds.
Candidate
The prefix sums are where each stretch ends. I draw an integer from one to the total and binary-search for the first prefix that is at least the draw.
Candidate
Setup is linear, each pick is log n. I'll keep the search in its own method so I can test every draw exhaustively, and if picks had to be constant time I'd mention the alias method.

Insert Delete GetRandom O(1) is the other randomness question in this set, about uniform picks from a set that changes. Snapshot Array uses the same rightmost-or-leftmost binary search reasoning inside a design problem. Top K Frequent Elements is a different take on weighting items, by counting rather than sampling.

Using Natively for practice

Natively, on Mac or Windows, can read this kind of problem from a screenshot during practice and propose a solution with code to set beside your own. Its Code hint action is handy for the boundary question in particular, when you get stuck on which search to use. The saved transcript lets you check that you explained the number-line picture clearly. See the AI interview assistant page.

Questions people ask

How do you solve Random Pick With Weight?

Build the running totals of the weights once. On each pick, draw a random integer from 1 to the total and binary-search for the first running total that is at least the draw. That index is returned with probability w[i] divided by the total.

What is the time complexity of Random Pick With Weight?

Setup is O(n) and each pick is O(log n), with O(n) extra space. The alias method makes each pick O(1) after O(n) setup, and a Fenwick tree supports changing weights in O(log n).

What is the common off-by-one bug in Random Pick With Weight?

Mixing up the draw range and the search. Draws from 1 to total pair with the first prefix at least the draw (bisect_left); draws from 0 to total - 1 pair with the first prefix strictly greater (bisect_right).

Why not repeat each index as many times as its weight?

That bag gives O(1) picks but needs sum(w) entries, which is hopeless when weights are in the millions. Prefix sums need only O(n) memory.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP