Event Log Selector with Window, Dedupe and Cap
Arrays & HashingAuto-graded · 20 test casesLast updated
Filter a list of event records by type, time window and id, then order them stably by timestamp and truncate, testing careful handling of optional arguments and ties.
You are given a log of records. Each record is a dictionary with these keys:
id(string): an identifier that may repeat across records.type(string): the category of the record.ts(integer): a timestamp in seconds since the epoch.payload(dictionary): arbitrary extra data. It is never inspected, only carried along.
Write a function that selects records from the log according to the optional rules below and returns them in a defined order.
Parameters
In this order:
events: the list of records.allowed_types: a list of strings, orNone.blocked_types: a list of strings, orNone.min_ts: an integer, orNone.max_ts: an integer, orNone.max_count: a non-negative integer, orNone.latest_per_id: a boolean.
Rules
Apply the steps in this order.
- Allowed types. If
allowed_typesis notNone, keep only records whosetypeappears in it. An empty list is a real filter that allows nothing, so the result is empty.Nonemeans no restriction. - Blocked types. If
blocked_typesis notNone, drop records whosetypeappears in it. A type listed in bothallowed_typesandblocked_typesis dropped. - Time window. Keep records with
min_ts <= ts <= max_ts. Both ends are inclusive, and each bound is applied only if it is notNone. Ifmin_ts > max_ts, nothing survives. - Per-id dedupe. If
latest_per_idisTrue, work on the records that survived steps 1 to 3. For each distinctid, keep only the record with the largestts. If several records of the sameidshare that largestts, keep the one that appears first in the input. - Ordering. Sort the remaining records by
tsascending. Records with equaltskeep their relative order from the original input. - Cap. If
max_countis notNone, return only the firstmax_countrecords of the sorted result.0gives an empty list, and a value larger than the result size returns everything.
Return a list of the original record dictionaries. Do not modify the input list or its records.
Constraints
0 <= len(events) <= 10^5- Every record has all four keys with the types described above.
max_count, when given, is>= 0.- Type names are compared by string equality.
- Aim for roughly
O(n log n)time.
Examples
Example 1
Input: select_events([{'id': 'a', 'type': 'click', 'ts': 30, 'payload': {'page': 'home'}}, {'id': 'b', 'type': 'view', 'ts': 10, 'payload': {}}, {'id': 'c', 'type': 'click', 'ts': 20, 'payload': {'page': 'pricing'}}], ['click'], None, None, None, None, False)
Output: [{'id': 'c', 'type': 'click', 'ts': 20, 'payload': {'page': 'pricing'}}, {'id': 'a', 'type': 'click', 'ts': 30, 'payload': {'page': 'home'}}]
Example 2
Input: select_events([{'id': 'a', 'type': 'click', 'ts': 5, 'payload': {}}, {'id': 'b', 'type': 'view', 'ts': 2, 'payload': {}}, {'id': 'c', 'type': 'purchase', 'ts': 7, 'payload': {}}, {'id': 'd', 'type': 'click', 'ts': 5, 'payload': {}}], None, ['purchase'], 5, 7, 2, False)
Output: [{'id': 'a', 'type': 'click', 'ts': 5, 'payload': {}}, {'id': 'd', 'type': 'click', 'ts': 5, 'payload': {}}]
Example 3
Input: select_events([{'id': 'x', 'type': 'login', 'ts': 10, 'payload': {'n': 1}}, {'id': 'y', 'type': 'login', 'ts': 8, 'payload': {'n': 2}}, {'id': 'x', 'type': 'logout', 'ts': 15, 'payload': {}}, {'id': 'z', 'type': 'login', 'ts': 15, 'payload': {}}], None, None, None, None, None, True)
Output: [{'id': 'y', 'type': 'login', 'ts': 8, 'payload': {'n': 2}}, {'id': 'x', 'type': 'logout', 'ts': 15, 'payload': {}}, {'id': 'z', 'type': 'login', 'ts': 15, 'payload': {}}]
Hints
Hint 1
Treat None as 'no restriction' using an `is not None` check, never a truthiness check, so an empty allowed list correctly yields nothing.
Hint 2
Do the cheap per-record checks first, remembering each survivor's original position. Then dedupe with a dictionary keyed by id, replacing an entry only when the new ts is strictly greater.
Hint 3
Sort by (ts, original_index) and apply the cap last, since 'first max_count' only makes sense after ordering. Convert the type lists to sets for fast lookups.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Do the work as a short pipeline, with each stage reducing or ordering the data for the next.
- Filter in one pass. Convert the type lists to sets so each membership test is O(1). Walk the events with
enumerate, skipping any event that fails the allowed-type, blocked-type or time-window checks. Keep each survivor together with its original index. - Dedupe (optional). Use a dictionary from
idto the best(event, index)seen so far. Replace an entry only when the newtsis strictly greater. Because the replacement is strict, among equal timestamps the earliest event in the input stays. - Sort by the key
(ts, original_index). This gives ascending time with ties broken by input order. Carrying the index explicitly keeps the tie-break correct even after the dictionary step. - Cap with a slice
[:max_count], only after sorting.
Why it is correct
- Optional arguments are tested with
is not None. An emptyallowed_typestherefore means "allow nothing" rather than "no filter". - The allowed and blocked checks are independent predicates on
type, so a type in both lists is always dropped. - Dropping only when
ts < min_tsorts > max_tsmakes both bounds inclusive, and each bound is independent. - Dedupe runs after filtering. If an id's newest record falls outside the window, an older in-window record of that id can still be the one kept.
- Slicing handles
0(empty result) and values larger than the list (everything) without special cases.
Complexity
- Time: O(n) for filtering and dedupe, plus O(m log m) to sort the m survivors, so O(n + m log m) overall.
- Space: O(m) for the survivor pairs and the dedupe dictionary. The event dictionaries themselves are not copied.
Reference solution
from typing import List, Optional
def select_events(events: List[dict], allowed_types: Optional[List[str]] = None, blocked_types: Optional[List[str]] = None, min_ts: Optional[int] = None, max_ts: Optional[int] = None, max_count: Optional[int] = None, latest_per_id: bool = False) -> List[dict]:
allowed = set(allowed_types) if allowed_types is not None else None
blocked = set(blocked_types) if blocked_types is not None else set()
survivors = []
for pos, ev in enumerate(events):
t = ev['type']
ts = ev['ts']
if allowed is not None and t not in allowed:
continue
if t in blocked:
continue
if min_ts is not None and ts < min_ts:
continue
if max_ts is not None and ts > max_ts:
continue
survivors.append((ev, pos))
if latest_per_id:
best = {}
for ev, pos in survivors:
cur = best.get(ev['id'])
if cur is None or ev['ts'] > cur[0]['ts']:
best[ev['id']] = (ev, pos)
survivors = list(best.values())
survivors.sort(key=lambda p: (p[0]['ts'], p[1]))
out = [ev for ev, _ in survivors]
return out if max_count is None else out[:max_count]