KatInterview

Weighted Lottery Ticket Assignment

Heaps, Sorting & SearchAuto-graded · 17 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searchprefix-sumsarrays

Last updated

Tests prefix sums and binary search to map ticket numbers into population-weighted ranges efficiently.

You are running a weighted lottery system where cities receive ticket ranges proportional to their population. Each city is assigned a contiguous block of consecutive ticket numbers, in the order given. City 0 receives tickets 1 through populations[0], city 1 receives tickets populations[0] + 1 through populations[0] + populations[1], and so forth.

Given a list of ticket numbers, determine which city owns each ticket.

Write a function assign_tickets(cities, populations, tickets) that returns a list of city names corresponding to each ticket number in the input order.

Constraints

  • 1 ≤ len(cities) = len(populations) ≤ 200,000
  • All city names are unique
  • 1 ≤ populations[i] ≤ 10^12
  • sum(populations) ≤ 2^53 - 1
  • Each ticket is an integer in [1, sum(populations)]
  • 0 ≤ len(tickets) ≤ 200,000
  • Tickets may appear in any order and may be repeated
  • A ticket number that falls exactly on a boundary between two cities belongs to the earlier city in the list

Notes

  • The sum of all populations defines the total ticket space
  • Ticket numbering starts at 1, not 0
  • Each city's range is contiguous and non-overlapping

Examples

Example 1

Input: assign_tickets(['A', 'B', 'C'], [2, 3, 1], [1, 2, 3, 5, 6])

Output: ['A', 'A', 'B', 'B', 'C']

Example 2

Input: assign_tickets(['Only'], [1000000000000], [1, 2, 999999999999, 1000000000000])

Output: ['Only', 'Only', 'Only', 'Only']

Example 3

Input: assign_tickets(['Paris', 'Tokyo', 'Lima'], [5, 1, 4], [10, 1, 6, 5, 10, 2])

Output: ['Lima', 'Paris', 'Tokyo', 'Paris', 'Lima', 'Paris']

Hints

Hint 1

Build an array of cumulative population totals to define the boundary of each city's ticket range.

Hint 2

For each ticket, find the first city whose cumulative total is greater than or equal to the ticket number.

Hint 3

Binary search on the cumulative array will locate the owning city in O(log n) time per ticket.