Return each user's first and last event in a single pass
events is a list of (user_id, timestamp) pairs in arbitrary order. Return a dict mapping each user to (first_ts, last_ts) — their earliest and latest event time.
Make a single pass — do not sort the whole list, and do not rescan it per user.
def first_last_events(events: list[tuple[str, int]]) -> dict[str, tuple[int, int]]:
# your code here
Write the implementation.
Keep a dict keyed by user. For each event, if the user is new store (ts, ts), otherwise widen the stored pair to (min(first, ts), max(last, ts)). One O(n) pass gives each user's earliest and latest time together — no sort, no per-user rescan.
- ✗Sorting the whole list when a single min/max pass suffices
- ✗Filtering per user, rescanning the list O(n*u) times
- ✗Assuming input order matches timestamp order
- →How would you also return each user's event count?
- →What changes if two events share a timestamp?
Keep a dict keyed by user. New user seeds (ts, ts); a repeat user widens its pair with min on the first slot and max on the last. One pass, O(n) time.
def first_last_events(events):
result = {}
for user, ts in events:
if user not in result:
result[user] = (ts, ts)
else:
first, last = result[user]
result[user] = (min(first, ts), max(last, ts))
return result
For [("a", 5), ("b", 2), ("a", 1), ("a", 9)] user a collapses to (1, 9) and b to (2, 2). There is no sort and no per-user filter — every event touches its user's pair exactly once, so the whole job is a single linear scan.