Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
ExperiencesCoaching
New
Practice
Mock InterviewsTimed interview simulations with feedbackSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Get started
Weighted Random Number Generator
00:00
5 left

Weighted Random Number Generator

MediumPython

Problem

Supermicro Computer evaluates several server configurations with different selection weights. Implement weighted sampling so that a configuration with weight w is selected with probability w / sum(weights).

To make the function deterministic and testable, the caller provides uniform random values instead of requiring the function to access a random-number library. For each random value, return the selected configuration index.

Formal Specification

Implement weighted_random(weights, random_values):

  • weights is a list of positive integers, where weights[i] is the relative probability of selecting configuration i.
  • random_values is a list of floating-point values, each in the interval [0, 1).
  • Return a list of indices, one for each random value.
  • A random value u corresponds to the target u * sum(weights) on the cumulative weight scale.
  • Use half-open intervals, so a target exactly equal to a cumulative boundary belongs to the interval beginning at that boundary.

Build the cumulative distribution once, then use binary search for every sample.

Constraints

  • 1 <= len(weights) <= 10^5
  • 1 <= weights[i] <= 10^9
  • 1 <= len(random_values) <= 10^5
  • Every random value satisfies 0 <= random_values[i] < 1

Function Signature

def weighted_random(weights, random_values):
Interviewer

Whenever you're ready, walk me through your approach or go straight to the code. The requirements are in the Question tab.

You need to log in / sign up to run or submit.
Code
Sign up free to run your codeLog inLn 2
Run your code to see test output here.