Ticket Ranges: Find the Bucket Owning Each Draw
Data Structure DesignAuto-graded · 14 test casesLast updated
Map integer draws to the index whose cumulative weight range contains them, using prefix sums and binary search, driven through a batch of init/query operations.
Ticket Ranges
A raffle assigns consecutive ticket numbers to buckets. You are given a list weights of positive integers. Bucket i owns exactly weights[i] tickets. Tickets are numbered starting at 1, and buckets are filled in index order: bucket 0 takes the first weights[0] tickets, bucket 1 takes the next weights[1], and so on.
For example, with weights = [1, 3, 2], bucket 0 owns ticket 1, bucket 1 owns tickets 2 to 4, and bucket 2 owns tickets 5 to 6.
A draw is a ticket number between 1 and the sum of all weights (inclusive). A draw x belongs to bucket i when the total weight of buckets 0..i-1 is strictly less than x, and the total weight of buckets 0..i is greater than or equal to x.
The function
Implement a function that simulates a sampler object through a batch of operations:
weights: the list of bucket weights.operations: a list of strings, each either"init"or"get_index".arguments: a list of the same length asoperations. For"init"the entry is an empty list. For"get_index"the entry is a list whose first element is the draw.
Process the operations in order and return a list of the same length as operations:
- For
"init", outputNone. - For
"get_index", output the 0-based index of the bucket that owns the draw. - For any other operation name, raise
ValueError.
The sampler is built from weights up front, so a "get_index" operation is valid regardless of where (or whether) "init" appears.
Constraints
1 <= len(weights)- Every
weights[i]is a positive integer. len(operations) == len(arguments)- Every draw is an integer between 1 and
sum(weights), inclusive. - A draw that equals a cumulative boundary belongs to the bucket that ends at that boundary.
- Aim for fast per-query lookup: preprocess once, then answer each draw in logarithmic time.
Examples
Example 1
Input: ticket_buckets([1, 3, 2], ['init', 'get_index', 'get_index', 'get_index'], [[], [2], [4], [6]])
Output: [None, 1, 1, 2]
Example 2
Input: ticket_buckets([2, 4], ['init', 'get_index', 'get_index'], [[], [2], [4]])
Output: [None, 0, 1]
Hints
Hint 1
Think of each bucket as owning a contiguous block of ticket numbers. The last ticket of each block is the running total of weights up to that bucket.
Hint 2
Because every weight is positive, the running totals are strictly increasing, so you can binary search them instead of scanning.
Hint 3
You want the first position whose running total is at least the draw. Be careful with draws that land exactly on a running total: they belong to the bucket that ends there, so choose the lower-bound style search rather than the upper-bound one.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each bucket owns a contiguous block of ticket numbers, and the last ticket of bucket i is the prefix sum prefix[i] = weights[0] + ... + weights[i]. A draw x belongs to the first bucket whose prefix sum is at least x.
So the algorithm is:
- Build the prefix sums once in O(n).
- For every
"get_index"operation, binary search the prefix array for the first position whose value is>= draw. This is exactly whatbisect_leftcomputes. - For
"init", appendNone. Any other operation raisesValueError.
Why it is correct
- All weights are positive, so the prefix array is strictly increasing, which makes binary search valid.
- The smallest index
iwithprefix[i] >= xsatisfies the right-hand condition by definition. Since it is the smallest,prefix[i-1] < xmust hold (otherwisei-1would qualify), which is the left-hand condition. Fori = 0the lower total is 0, which is below any draw of at least 1. - Draws lie in
[1, total]and the last prefix equalstotal, so a valid index always exists. - A draw equal to
prefix[i]maps toibecausebisect_leftstops at the first element that is>=the target.bisect_rightwould be off by one on boundaries.
Complexity
- Preprocessing: O(n) time, O(n) space.
- Each query: O(log n) time, O(1) extra space.
- Total: O(n + q log n) for
qoperations, plus O(q) for the output.
Reference solution
from bisect import bisect_left
from typing import List, Optional
def ticket_buckets(weights: List[int], operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
prefix = []
total = 0
for w in weights:
total += w
prefix.append(total)
results = []
for op, args in zip(operations, arguments):
if op == "init":
results.append(None)
elif op == "get_index":
results.append(bisect_left(prefix, args[0]))
else:
raise ValueError("Unknown operation")
return results