Problem · Array
Select a City by Population Weight
Learn this problemProblem statement
You are given parallel arrays cities and populations. Each positive population is the selection weight of the city at the same index.
You are also given a zero-based integer ticket in the range from 0 through the total population minus one. Assign consecutive ticket ranges to cities in input order, with each range length equal to that city's population.
Return the city whose range contains ticket. If a ticket is chosen uniformly from the valid range, this deterministic mapping selects every city with probability proportional to its population.
Function
selectCityByPopulation(cities: String[], populations: int[], ticket: int) → StringExamples
Example 1
cities = ["Alpha","Beta","Gamma"]populations = [2,3,5]ticket = 0return = "Alpha"Alpha owns tickets 0 and 1.
Example 2
cities = ["Alpha","Beta","Gamma"]populations = [2,3,5]ticket = 4return = "Beta"Beta owns tickets 2, 3, and 4.
Example 3
cities = ["North","South"]populations = [1,9]ticket = 9return = "South"South owns tickets 1 through 9, including the final valid ticket.
Constraints
1 <= cities.length = populations.length <= 100000.- Every city name is nonempty, and city names are distinct.
1 <= populations[i].- The total population is at most
2,000,000,000. 0 <= ticket < sum(populations).