← 返回 snapchat 的题目列表Event Count Query over Timestamp Range
类型:qbank
Preprocess unordered and duplicate event timestamps, then answer count queries for arbitrary start and end timestamps.
Requirements
Given a list of event timestamps, implement a query function:
class EventCounter:
def __init__(self, timestamps: list[int]): ...
def query(self, start: int, end: int) -> int: ...
Expected behavior:
Input timestamps may be unordered.
Duplicate timestamps count as multiple events.
query(start, end) returns the number of events in the inclusive or clarified time range.
Multiple queries should be faster than scanning the whole event list each time.
Handle empty input and ranges outside the observed timestamp span.
Notes
The simplest preprocessing is to sort all timestamps and answer each query with binary search: right = bisect_right(times, end), left = bisect_left(times, start), answer right - left. This naturally handles duplicate timestamps.
If the interviewer wants explicit aggregation, compress timestamps into (time, count) pairs and build a prefix-count array. Then binary-search compressed times and subtract prefix sums. This is useful when there are many duplicate timestamps or when you also need per-time counts.
Construction is O(n log n) for sorting. Query is O(log n) with sorted raw timestamps or O(log u) with u unique timestamps. Space is O(n) or O(u).
Preparation
Implement both raw sorted timestamps and compressed-prefix variants.
Clarify endpoint semantics before coding: [start, end], [start, end), or (start, end].
Test duplicate timestamps, no events in range, full range, and reversed start > end if allowed.