Seller Enforcement Timeline and Repeat-Buyer Product Filters
SQL & DataModel answerLast updated
Three SQL/pandas tasks: find sellers penalized after a reinstatement, get the first event after the latest reinstatement, and find customers who bought A in 2010 and B in 2018.
Context
A marketplace's trust and safety team keeps a log of enforcement actions on sellers. A separate analytics team studies what customers buy over time. You are given two tables.
seller_status: one row per status change for a seller.
| seller_id | date | status |
|---|---|---|
| 1 | 2019-01-01 | reinstate |
| 1 | 2020-06-01 | block |
| 2 | 2020-01-01 | reinstate |
| 2 | 2021-03-01 | suspend |
purchase_history: one row per item ordered.
| id | order_date | product |
|---|---|---|
| 10 | 2010-05-02 | A |
| 10 | 2018-07-19 | B |
| 11 | 2010-03-11 | A |
Here id identifies the customer. Statuses include reinstate, block and suspend.
Tasks
Write SQL (or pandas) for each of the following:
- Return every
seller_idthat has at least oneblockorsuspendevent dated after at least onereinstateevent. - For every seller, return the first status recorded after that seller's most recent
reinstate. - Return every customer
idthat bought product'A'at least once during 2010 and product'B'at least once during 2018.
What to cover
- State your assumptions, such as same-day events, sellers with no reinstate, and sellers with nothing after their latest reinstate.
- Give the expected output on the sample data.
- Briefly discuss complexity and how you would handle messy data.
Hints
Hint 1
For task 1, you don't need a self-join. Ask what single comparison between one reinstate date and one block/suspend date proves that a valid ordered pair exists.
Hint 2
For task 2, first attach each seller's latest reinstate date to all of their rows (a window MAX over a CASE expression). Then keep only later rows and number them by date.
Hint 3
For task 3, group by customer and use conditional counts in HAVING, one per product/year condition. Prefer half-open date ranges over extracting the year.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
The three tasks each test a different pattern:
- Ordering of events within a group. Reduce it to a MIN versus MAX comparison.
- First event after an anchor. Compute the anchor per group, filter, then rank.
- Two conditions on the same entity. Use grouped conditional counts, which amounts to a set intersection.
Task 1: penalty after any reinstatement
A valid pair (reinstate date r, penalty date p, with r < p) exists if and only if the earliest reinstate is earlier than the latest penalty.
- If some pair works, then
min(r) <= r < p <= max(p), so the inequality holds. - If
min(r) < max(p), those two events are themselves a valid pair.
SELECT seller_id
FROM seller_status
GROUP BY seller_id
HAVING MIN(CASE WHEN status = 'reinstate' THEN date END)
< MAX(CASE WHEN status IN ('block','suspend') THEN date END);
A seller lacking either kind of event gets a NULL on one side. The comparison is then unknown and HAVING drops the seller, which is the behavior we want. This is one hash aggregation pass, O(n).
A common mistake is a self-join on all pairs of rows. It works, but it is quadratic per seller and can produce duplicates that need a DISTINCT.
Task 2: first status after the latest reinstatement
WITH anchored AS (
SELECT seller_id, date, status,
MAX(CASE WHEN status = 'reinstate' THEN date END)
OVER (PARTITION BY seller_id) AS last_reinstate
FROM seller_status
),
ranked AS (
SELECT seller_id, date, status,
ROW_NUMBER() OVER (PARTITION BY seller_id
ORDER BY date, status) AS rn
FROM anchored
WHERE date > last_reinstate
)
SELECT seller_id, status AS first_status_after_reinstate, date
FROM ranked
WHERE rn = 1;
How it works:
- The window
MAXstamps each row with its seller's latest reinstate date. WHERE date > last_reinstatekeeps only strictly later events. Sellers with no reinstate have aNULLanchor and disappear.ROW_NUMBERordered by date picks the earliest remaining event. Addingstatusas a second sort key makes ties deterministic. If the table has a sequence number or timestamp, use that instead.
Cost is O(n log n) because of the per-partition sort.
Task 3: A in 2010 and B in 2018
SELECT id
FROM purchase_history
GROUP BY id
HAVING SUM(CASE WHEN product = 'A'
AND order_date >= '2010-01-01'
AND order_date < '2011-01-01' THEN 1 ELSE 0 END) > 0
AND SUM(CASE WHEN product = 'B'
AND order_date >= '2018-01-01'
AND order_date < '2019-01-01' THEN 1 ELSE 0 END) > 0;
Half-open ranges behave the same across dialects and work for both DATE and TIMESTAMP columns. They also let an index on (product, order_date) prune rows, which wrapping the column in YEAR() would prevent. Duplicate rows are harmless because the test is > 0.
An equivalent form is INTERSECT of two filtered SELECT DISTINCT id queries. It is clearer to read, but it scans the table twice.
Expected output on the sample data
- Task 1: sellers 1 and 2.
- Task 2: (1, block) and (2, suspend).
- Task 3: customer 10. Customer 11 never bought B in 2018.
pandas version
import pandas as pd
def penalized_after_reinstate(status: pd.DataFrame) -> list:
s = status.assign(date=pd.to_datetime(status["date"]))
first_r = s[s.status == "reinstate"].groupby("seller_id")["date"].min()
last_p = (s[s.status.isin(["block", "suspend"])]
.groupby("seller_id")["date"].max())
both = pd.concat([first_r.rename("r"), last_p.rename("p")],
axis=1).dropna()
return sorted(both.index[both["r"] < both["p"]])
def first_status_after_last_reinstate(status: pd.DataFrame) -> pd.DataFrame:
s = status.assign(date=pd.to_datetime(status["date"]))
last_r = (s[s.status == "reinstate"]
.groupby("seller_id")["date"].max()
.rename("last_reinstate"))
s = s.join(last_r, on="seller_id")
after = s[s["date"] > s["last_reinstate"]]
first = (after.sort_values(["seller_id", "date", "status"])
.groupby("seller_id", as_index=False).first())
return first[["seller_id", "status", "date"]]
def buyers_a2010_b2018(p: pd.DataFrame) -> list:
p = p.assign(order_date=pd.to_datetime(p["order_date"]))
a = set(p.loc[(p["product"] == "A") & (p.order_date.dt.year == 2010), "id"])
b = set(p.loc[(p["product"] == "B") & (p.order_date.dt.year == 2018), "id"])
return sorted(a & b)
Complexity
| Task | Time | Space |
|---|---|---|
| 1 | O(n) | O(sellers) |
| 2 | O(n log n) | O(n) |
| 3 | O(n) | O(customers) |
Edge cases and trade-offs
- Same-day events. I use strict
>, so a block on the same date as a reinstate does not count as "after". Without a timestamp or sequence column the true order is unknowable, so say so explicitly and ask whether one exists. - "Any" versus "most recent" reinstate in Task 1. A seller who was reinstated, blocked, then reinstated again qualifies under "after any reinstate" but not under "after the most recent". Confirm which reading is wanted. The two tasks deliberately differ here.
- Nothing after the latest reinstate. The seller is in good standing, so Task 2 omits them. If the business wants every seller listed,
LEFT JOINfrom a sellers table and returnNULL. - Sellers with no reinstate. Excluded from Tasks 1 and 2 by
NULLsemantics. - Dirty data. Normalize status and product with
LOWER(TRIM(...)), handleNULLdates, and cast string dates before comparing, since string comparison only works for ISO format. - Scale. Index
seller_statuson(seller_id, date)so the window sort can reuse the index order. For very large logs, Task 2 can also be done by joining to a pre-aggregated table of each seller's latest reinstate date.
Common mistakes
- Comparing against the first penalty instead of the last in Task 1, which misses sellers with an early penalty followed by a later one.
- Using
>=and silently counting same-day events. - Applying
WHEREfilters on product and year inside one query and then requiring both. A row can't be both A and B, so the result is always empty. The conditions must be evaluated per group. - Forgetting a tie-breaker in
ROW_NUMBER, which makes output nondeterministic.