Generate Weighted Random Keys With Add And Remove
Design a class WeightedKeyGenerator that stores string keys, each associated with a positive integer weight.
Implement the following methods:
add_key(key: str, weight: int): Inserts a new key-value pair or updates the weight of an existing key.remove_key(key: str): Removes a key from the generator.generate() -> str: Returns a single key randomly. The probability of returning a specific key should be proportional to its current weight.
Constraints:
- Weights are always positive integers.
- Calling
generate()on an empty generator is an invalid operation.
Follow-up: Discuss how to efficiently support updates and removals, considering data structures like segment trees or Fenwick trees for optimized performance.
Example:
If keys are {'a': 1, 'b': 3}, generate() should return 'b' approximately three times more often than 'a' over many calls.
AI interview prep
Core dilemma
Balancing efficient weighted random selection with the overhead of dynamic key additions, updates, and removals.
3 tradeoffs and 3 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Generate Weighted Random Keys With Add And Remove
Design a class WeightedKeyGenerator that stores string keys, each associated with a positive integer weight.
Implement the following methods:
add_key(key: str, weight: int): Inserts a new key-value pair or updates the weight of an existing key.remove_key(key: str): Removes a key from the generator.generate() -> str: Returns a single key randomly. The probability of returning a specific key should be proportional to its current weight.
Constraints:
- Weights are always positive integers.
- Calling
generate()on an empty generator is an invalid operation.
Follow-up: Discuss how to efficiently support updates and removals, considering data structures like segment trees or Fenwick trees for optimized performance.
Example:
If keys are {'a': 1, 'b': 3}, generate() should return 'b' approximately three times more often than 'a' over many calls.