KatInterview

Build a Sampler That Picks Items in Proportion to Mutable Weights

Data Structure DesignModel answer
MediumModel answerData Structure Designfenwick-treeweighted-samplingrandomization

Last updated

Design a structure holding items with positive integer weights that supports insert, delete and a weight-proportional random pick, each in logarithmic time.

Weighted Lottery with Changing Membership

You are building a "lottery drawer" for a service. It stores a changing collection of entries. Each entry has a unique identifier and a positive integer weight. The drawer must support these operations:

  1. insert(id, weight) adds an entry with the given weight. If id is already present, you decide whether to reject the call or treat it as a weight update. State your choice.

  2. delete(id) removes the entry if it is present.

  3. sample() returns one identifier at random, where the chance of returning id is

    weight(id) / (sum of all current weights)

Constraints

  • Each operation should run in O(log n) time, where n is the number of stored entries.
  • Plan for up to about 10^5 operations in total.
  • A single weight can be as large as 10^9, so the total weight can exceed the range of a 32-bit integer.
  • With a perfect random source, sample() must be exactly unbiased.

Assumptions

  • You have a helper randInt(1, totalWeight) that returns a uniformly distributed integer in the inclusive range.
  • Identifiers come and go over time, so you must say clearly how an identifier is tied to an internal position in your structure as the set changes.

What to deliver

Describe the data structure, explain how each operation works, argue why sampling is exactly proportional, give the complexity, discuss edge cases (empty set, duplicates, missing deletes, overflow), and provide working code.

Hints

Hint 1

Imagine laying every entry's weight end to end along a number line from 1 to the total. A uniform random integer in that range lands inside exactly one entry's segment, and the segment length equals the entry's weight.

Hint 2

Finding the segment that contains a random value is a prefix-sum search: locate the first position whose running total is at least the drawn value. Which structure supports both point updates and prefix queries in O(log n)?

Hint 3

Do not shift positions when deleting. Keep a map from id to a stable slot, a reverse map from slot to id, and a pool of freed slots. A freed slot has weight 0, so it owns no integers and can never be drawn.