Skip to content

Events and time

Python rounds often deal with events and periods in time: webhooks that arrive twice or late, access periods that overlap, renewal dates at the end of a month, a fast count of active subscriptions per day. Each task is a small class or function, and its bugs hide at the boundaries: equal timestamps, touching periods, 31 January, a subscription that starts at 10:00. The tasks build on Sets and duplicates, Intervals and Dates and durations. To rehearse under real conditions, the mock interview page gives you a random task with the clock running and the hints hidden.

PythonP02 · Difficulty: medium · Target time: 20 min

The sales channels send us webhooks about subscriptions: purchased, renewed, expired, refunded. Delivery is at least once, so the same event can arrive twice. The order is not guaranteed either: an old event can arrive after a newer one.

Write a class EventProcessor. process(event) handles one event and returns True if it is new, or False if we have already seen this event_id — then nothing changes. state(customer) returns the customer's current status: active, expired or refunded, or None if we know nothing about this customer.

If an event is older (smaller ts) than the last event we applied for this customer, it does not change the status, but it still counts as processed. With equal ts, the one processed later wins. An unknown event type is a ValueError, and that event is not marked as processed.

process(e2, refund,  c1, ts=300) → True;  state(c1) = refunded
process(e1, renewal, c1, ts=200) → True;  state(c1) = refunded   # arrived late, not applied
process(e1 again)                → False
Full statement (as in the task file)
Channel webhooks arrive at least once and not always in order. Write `EventProcessor`:

    p = EventProcessor()
    p.process({"event_id": "e1", "type": "purchase", "customer": "c1", "ts": 100})  # -> True
    p.process({"event_id": "e1", ...})   # same id again -> False, nothing changes
    p.state("c1")                        # -> "active"

- `process(event) -> bool`: False if this event_id was already processed, True otherwise.
- The status of a customer comes from the event type:
      purchase, renewal -> "active";  expiration -> "expired";  refund -> "refunded"
- Out of order: if an event is OLDER (smaller ts) than the last event applied for that customer, it does not change the status. It still counts as processed (True, and a repeat returns False).
- Equal ts: the later-processed event wins.
- `state(customer)` returns the status or None for an unknown customer.
- Unknown event type -> ValueError (and the event is NOT marked as processed).

Ask first

Say each question out loud before you code. Open the interviewer's answer only after you asked.

  1. Is the processed-ids set allowed to grow forever?

    Yes for this exercise; say how you would limit it in production.

  2. Can events arrive out of order?

    Yes. An older event must not overwrite a newer status, but it still counts as processed.

  3. Two events for a customer with the same ts?

    The one processed later wins.

  4. Unknown event type?

    ValueError, and the event is not marked as processed.

class EventProcessor:
    def __init__(self):
        raise NotImplementedError("your code")

    def process(self, event) -> bool:
        raise NotImplementedError("your code")

    def state(self, customer):
        raise NotImplementedError("your code")

Run executes the file top to bottom, like python file.py. Check imports it as a module and runs the tests.

Hint: what the interviewer would nudge

You need two pieces of state: the event ids you have processed, and the last applied event per customer. Decide the order of the checks before you write them.

Reference solution
STATUS = {"purchase": "active", "renewal": "active", "expiration": "expired", "refund": "refunded"}
class EventProcessor:
def __init__(self):
self._seen = set() # production: a unique constraint on event_id, or ids with a TTL
self._customers = {} # customer -> (ts of last applied event, status)
def process(self, event) -> bool:
if event["event_id"] in self._seen:
return False
if event["type"] not in STATUS:
raise ValueError(f"unknown event type: {event['type']}")
self._seen.add(event["event_id"])
last = self._customers.get(event["customer"])
if last is None or event["ts"] >= last[0]:
self._customers[event["customer"]] = (event["ts"], STATUS[event["type"]])
return True
def state(self, customer):
last = self._customers.get(customer)
return last[1] if last else None
WalkthroughTry the task first: the walkthrough is most useful after your own attempt.

What it is for. The sales channels send events at least once and not always in order. A repeat must change nothing, and an old event must not overwrite a newer status.

Steps. Keep a set of processed event_ids and a dict from customer to (ts, status). For each event:

  1. A known id → return False.
  2. Check the type first: an unknown type → ValueError.
  3. Mark the id as processed.
  4. Apply the status only if ts >= the ts of the last applied event; return True either way.

Traps.

  • Marking the id before the type check. A broken event then counts as processed and can never be handled again.
  • > instead of >= breaks the rule “with equal ts, the later-processed event wins”.
  • A late, older event still returns True: it is processed, it just does not change the status.

Complexity. O(1) per event on average. Memory grows with the number of event ids, which the task allows.

In production. Deduplication is a unique key in the database (INSERT … ON CONFLICT DO NOTHING) or ids kept with a TTL, not a set in the memory of one process. Several workers and a restart would both break the in-memory version.

PythonP03 · Difficulty: medium · Target time: 15 min

A customer can have access periods that overlap: they upgraded in the middle of a month, or got a promo on top of a paid plan. Support wants to see when the customer actually had access, without the overlaps.

Write two functions. merge_periods merges periods that overlap or touch (one ends exactly when the next starts) and returns them sorted. total_access returns the total time with access, so overlapping time is counted once.

A period is a (start, end) pair, and the end is not included. An empty list gives [] and timedelta(0). A period with end <= start is a ValueError.

periods (days of September):  1–10, 5–20, 20–25, 30–31
merge_periods → 1–25, 30–31          # 1–10 and 5–20 overlap, 20–25 touches
total_access(1–10, 5–20) → 19 days     # not 9 + 15 = 24
Full statement (as in the task file)
A customer can have overlapping periods (an upgrade in the middle of a month, a promo on top of a paid plan). Support wants to see WHEN the customer had access, without overlaps.

    merge_periods([(d(1), d(10)), (d(5), d(20)), (d(20), d(25)), (d(30), d(31))])
    -> [(d(1), d(25)), (d(30), d(31))]

- Input: a list of (start, end) datetimes, any order; each period is [start, end).
- Periods that overlap OR touch (end == next start) merge into one.
- Output: sorted by start, no overlaps.
- `total_access(periods) -> timedelta`: total time with access (overlaps counted once).
- An empty list -> [] and timedelta(0). A period with end <= start -> ValueError.

Ask first

Say each question out loud before you code. Open the interviewer's answer only after you asked.

  1. Can the input be very large?

    Up to a million periods: O(n log n) is fine, O(n^2) is not.

  2. Do periods that only touch (end == next start) merge?

    Yes, they merge into one.

  3. Is the input sorted?

    No, it can be in any order.

  4. What about a period with end <= start?

    It is invalid: ValueError.

from datetime import timedelta


def merge_periods(periods):
    raise NotImplementedError("your code")


def total_access(periods) -> timedelta:
    raise NotImplementedError("your code")

Run executes the file top to bottom, like python file.py. Check imports it as a module and runs the tests.

Hint: what the interviewer would nudge

What becomes easier if the periods are sorted by start? Then walk through them once: what do you need to remember to decide whether the next period joins the current one?

Reference solution
from datetime import timedelta
def merge_periods(periods):
for start, end in periods:
if end <= start:
raise ValueError(f"empty or negative period: {start} .. {end}")
merged = []
for start, end in sorted(periods):
if merged and start <= merged[-1][1]: # overlaps or touches
merged[-1] = (merged[-1][0], max(merged[-1][1], end))
else:
merged.append((start, end))
return merged
def total_access(periods) -> timedelta:
return sum((end - start for start, end in merge_periods(periods)), timedelta(0))
WalkthroughTry the task first: the walkthrough is most useful after your own attempt.

What it is for. Support wants to see when a customer had access. An upgrade or promo access on top of a paid plan creates overlaps. They must not be counted twice, especially if total_access is used to compute compensation.

Steps.

  1. Validate every period before sorting: end <= start → ValueError.
  2. Sort by start.
  3. One pass: if the next start is <= the end of the last merged period, extend that period to max(end); otherwise start a new one.
  4. total_access is the sum of end - start over the merged periods, with timedelta(0) as the start value.

Traps.

  • Touching periods (end equals the next start) also merge, so the comparison is <=, not <.
  • You need max(end): a period inside another one must not shorten the merged period.
  • sum() of timedeltas needs the start value timedelta(0). The default start is the integer 0, and 0 + timedelta raises TypeError.

Complexity. O(n log n) for the sort; the pass itself is O(n). A million periods is fine, while comparing every pair, O(n²), is not.

P04. Renewal dates from ISO 8601 durations

Section titled “P04. Renewal dates from ISO 8601 durations”
PythonP04 · Difficulty: medium · Target time: 20 min

Subscriptions are sold for periods written in ISO 8601 format: "P1W" is a week, "P1M" a month, "P3M" three months, "P1Y" a year. We need to compute renewal dates.

add_duration(dt, duration) returns the date one period later. Months and years stick to the end of the month: January 31 + one month is February 28 (or 29 in a leap year). The time of day stays the same. Anything other than PnD, PnW, PnM or PnY with a positive n is a ValueError.

renewal_dates(start, duration, until) returns every period start that is before until, beginning with start. Compute each one from the original start (start + k periods), not from the previous date — otherwise 31 → 28 → 28.

add_duration(Jan 31, 'P1M') → Feb 28
renewal_dates(Jan 31, 'P1M', until=May 1)
→ Jan 31, Feb 28, Mar 31, Apr 30        # not Mar 28!
Full statement (as in the task file)
Plans have durations like "P1W", "P1M", "P3M", "P1Y". Write:

    add_duration(datetime(2026, 1, 31), "P1M")  -> datetime(2026, 2, 28)
    renewal_dates(datetime(2026, 1, 31), "P1M", until=datetime(2026, 5, 1))
        -> [2026-01-31, 2026-02-28, 2026-03-31, 2026-04-30]

- Supported: PnD, PnW, PnM, PnY with a positive integer n. Anything else -> ValueError.
- Months and years clamp to the last day of the month (Jan 31 + P1M = Feb 28, or Feb 29 in a leap year). The time of day stays the same.
- `renewal_dates(start, duration, until)`: all period starts that are < until, starting with `start`. IMPORTANT: compute each date from the ORIGINAL start (start + k * duration), not from the previous date. Otherwise Jan 31 -> Feb 28 -> Mar 28 drifts; the customer expects Mar 31.

Ask first

Say each question out loud before you code. Open the interviewer's answer only after you asked.

  1. Mixed durations like "P1M2D"?

    Not needed; say how you would extend the parser.

  2. What if duration is None or not a string?

    ValueError as well.

def add_duration(dt, duration):
    raise NotImplementedError("your code")


def renewal_dates(start, duration, until):
    raise NotImplementedError("your code")

Run executes the file top to bottom, like python file.py. Check imports it as a module and runs the tests.

Hint: what the interviewer would nudge

Do not add a month to the previous date. Compute each renewal from the original start, then clamp the day to the last day of the target month.

Reference solution
import calendar
import re
from datetime import timedelta
_PATTERN = re.compile(r"P([1-9]\d*)([DWMY])")
def _parse(duration):
if not isinstance(duration, str): # None, 12, b"P1M": re would raise TypeError
raise ValueError(f"duration must be a string, got {duration!r}")
m = _PATTERN.fullmatch(duration)
if not m:
raise ValueError(f"unsupported duration: {duration!r}")
return int(m.group(1)), m.group(2)
def _add_months(dt, months):
total = dt.month - 1 + months
year, month = dt.year + total // 12, total % 12 + 1
day = min(dt.day, calendar.monthrange(year, month)[1])
return dt.replace(year=year, month=month, day=day)
def _add(dt, n, unit):
if unit == "D":
return dt + timedelta(days=n)
if unit == "W":
return dt + timedelta(weeks=n)
return _add_months(dt, n if unit == "M" else 12 * n)
def add_duration(dt, duration):
n, unit = _parse(duration)
return _add(dt, n, unit)
def renewal_dates(start, duration, until):
n, unit = _parse(duration)
dates, k = [], 0
while True:
current = _add(start, k * n, unit) # always from the original start: no drift
if current >= until:
return dates
dates.append(current)
k += 1
WalkthroughTry the task first: the walkthrough is most useful after your own attempt.

What it is for. Renewal dates for ISO 8601 periods. A customer who bought on 31 January expects renewals on 28 February and 31 March, not on 28 March.

The idea. Compute each date from the original start, as start + k periods, and clamp it to the last day of the month. If you add one month to the previous date instead, the day drifts:

MethodRenewal dates
start + k monthsJan 31, Feb 28, Mar 31, Apr 30
previous date + 1 monthJan 31, Feb 28, Mar 28, Apr 28

Steps.

  1. Parse strictly: first check isinstance(duration, str), then re.fullmatch(r"P([1-9]\d*)([DWMY])", duration). Anything else → ValueError.
  2. Days and weeks are a timedelta.
  3. Months: count the target year and month, then calendar.monthrange(year, month)[1] gives the last day, and the day is the smaller of the two. A year is 12 months.

Traps.

  • timedelta has no months, and dt.replace(month=2) on 31 January raises ValueError. Python 3.14, the one on this site, says day 31 must be in range 1..28 for month 2 in year 2026; older versions say day is out of range for month. The wording differs by version, so test for ValueError, not for the message.
  • re.match instead of re.fullmatch accepts “P1M2D”, because the start of the string matches.
  • None, 12 or b"P1M" must give ValueError, not TypeError. re.fullmatch raises TypeError for anything that is not a str, so check the type first. duration or "" is not enough: it fixes only None.

Follow-up. “How would you support P1M2D?” Parse the parts one by one and add the larger units first: years and months, then weeks and days.

PythonP05 · Difficulty: hard · Target time: 20 min

This is the same question as SQL Q04 — how many subscriptions are active on each day — but in Python and for a lot of data.

The input is a list of subscriptions (start, end), where the end is not included, and a range of days. A subscription is active on day D if it is active at 00:00 of that day. Return a dict with EVERY day of the range, even if the count is zero.

Speed matters: 200,000 subscriptions over 365 days must take well under 2 seconds. Checking every subscription for every day is 73 million checks — too slow. Check in the browser allows 4 seconds, because Python there is 2–3 times slower.

subscriptions: Sep 1 00:00 – Sep 3 00:00;  Sep 1 10:00 – Sep 5;  Aug 20 – Oct 1
days Sep 1–5 → {1: 2, 2: 3, 3: 2, 4: 2, 5: 1}
# on the 1st the second one has not started yet (10:00); on the 3rd the first one has ended
Full statement (as in the task file)
Same question as SQL Q04, but in Python and for a lot of data.

    daily_active_counts(subscriptions, first_day=date(2026, 9, 1), last_day=date(2026, 9, 30))
    -> {date(2026, 9, 1): 1068, date(2026, 9, 2): 1063, ...}

- `subscriptions`: a list of (start, end) datetimes, period [start, end).
- A subscription is active on day D if it is active at 00:00 of D: start <= D 00:00 < end.
- Return a dict with EVERY day from first_day to last_day inclusive (0 if nobody is active).
- Must handle 200,000 subscriptions and 365 days in well under 2 seconds. The naive "for each day, for each subscription" is 73 million checks — too slow. (Check in the browser allows 4 seconds: Python there is 2-3 times slower.)

Ask first

Say each question out loud before you code. Open the interviewer's answer only after you asked.

  1. Is a subscription that starts at 10:00 active on that day?

    No: active on day D means active at 00:00 of D.

def daily_active_counts(subscriptions, first_day, last_day):
    raise NotImplementedError("your code")

Run executes the file top to bottom, like python file.py. Check imports it as a module and runs the tests.

Hint: what the interviewer would nudge

One subscription changes the daily count on only two days. Which two? If you write down just those changes, how do you get the count for every day of the range?

Reference solution
from collections import defaultdict
from datetime import datetime, time, timedelta
def _first_midnight_at_or_after(dt):
midnight = datetime.combine(dt.date(), time())
return dt.date() if dt == midnight else dt.date() + timedelta(days=1)
def daily_active_counts(subscriptions, first_day, last_day):
delta = defaultdict(int) # day -> change in the active count at 00:00
for start, end in subscriptions:
first_active = _first_midnight_at_or_after(start) # first midnight with start <= midnight
first_inactive = _first_midnight_at_or_after(end) # first midnight with midnight >= end
if first_active < first_inactive:
delta[first_active] += 1
delta[first_inactive] -= 1
# everything that changed before the window is already "in" at first_day
running = sum(v for day, v in delta.items() if day <= first_day)
result, day = {}, first_day
while day <= last_day:
if day != first_day:
running += delta.get(day, 0)
result[day] = running
day += timedelta(days=1)
return result
WalkthroughTry the task first: the walkthrough is most useful after your own attempt.

What it is for. The same question as SQL Q04 on Subscriptions over time, but on 200,000 subscriptions over a year. “Every day × every subscription” is 73 million checks, so it needs a faster algorithm.

Steps. A difference array, also called a sweep line:

  1. For each subscription, find the first midnight at or after start: the first active day. Find the first midnight at or after end: the first day it is no longer active. If they are the same day, the subscription is never active at a midnight; skip it.
  2. Add +1 on the first day and −1 on the second, in a dict from day to change.
  3. Walk the days from first_day to last_day with a running sum. The changes before first_day go into the starting value.

Traps.

  • A subscription that starts at 10:00 is active only from the next day. One that starts exactly at midnight is active on that day.
  • Subscriptions that started before the range still count: add their changes to the starting value, do not drop them.
  • Every day of the range must be in the result, even with 0.

Check. On the practice data the result equals Q04: 1 September — 1068, 2 September — 1063.

Complexity. O(n + days) instead of O(n × days), with memory for one change per distinct day. Sorting the changes instead of bucketing them gives O(n log n), which is also fine.

Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.