Distinct Users with Post-Signup Activity
Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen
Problem Statement
Given user registration records and product activity logs, count how many distinct registered accounts triggered at least one event at or after their registration timestamp.
The two input datasets represent:
users: account rows containinguser_id,signup_date, and optionallyplan_type.events: activity rows containinguser_idandevent_ts.
Implement:
def count_users_with_event(users: List[List[str]], events: List[List[str]]) -> int:
(In PostgreSQL, write a single read-only SELECT query returning one row with a single column users_with_event.)
Apply these rules:
- Match activity to registrations on
user_idand requireevent_ts >= signup_date(an event at the exact registration second qualifies; an event even one second earlier does not). - Count each qualifying
user_idonce regardless of how many post-signup events they logged. - Ignore events whose
user_iddoes not appear inusers, and ignore rows whereuser_id,signup_date, orevent_tsisNone(NULL). - If the same
user_idappears in multipleusersrows, an event at or after any validsignup_datefor that user qualifies them. - Return
0when nobody qualifies.
Examples
Example 1
Input:
users = [
[10, "2025-03-10 14:00:00", "starter"],
[20, "2025-03-12T08:30:00", "pro"],
[30, "2025-03-15", "starter"],
[40, "2025-03-18 09:00:00", "team"],
]
events = [
[10, "2025-03-10 14:00:00"],
[10, "2025-03-11 09:15:00"],
[20, "2025-03-12T08:29:59"],
[30, "2025-03-15 00:00:00"],
[99, "2025-03-20 12:00:00"],
]
Output: 2
Explanation: Account 10 qualifies via two post-signup events (counted once), and account 30 qualifies because a bare date '2025-03-15' represents 00:00:00 midnight, tying '2025-03-15 00:00:00'. Account 20's event occurred 1 second before registration, account 40 has no events, and 99 is not a registered account.
Example 2
Input:
users = [
["acct_a", "2025-08-05T18:00:00"],
["acct_b", "2025-08-06"],
]
events = [
["acct_a", "2025-08-04"],
["acct_b", "2025-08-05 23:59:59"],
]
Output: 0
Explanation: Both activity timestamps fall strictly before their owners' registration instants (acct_b's event is 1 second before 2025-08-06 00:00:00), so 0 accounts qualify.
Constraints
- Timestamp strings use
'YYYY-MM-DD','YYYY-MM-DD HH:MM:SS', or'YYYY-MM-DDTHH:MM:SS'(bare dates denote midnight00:00:00), orNone(NULL). - Each
usersrow starts with[user_id, signup_date](with an optional third elementplan_type); eacheventsrow is[user_id, event_ts]. usersandeventscan be empty, contain duplicate rows, or containNone(NULL) values.
Step-by-step walkthrough
Understand the tables, rules, and input shapes
We are given two tables—
users(user_id, signup_date, plan_type)andevents(user_id, event_ts)—and asked to count how many distinct users have at least one event at or after theirsignup_date.Keep four rules front and center:
- Inclusive comparison (
>=): An event at the exact instant ofsignup_datequalifies; an event even 1 second beforesignup_datedoes not. - Distinct users, not events: A user with ten qualifying events adds
1to the total, not10. - Registered users only: Events whose
user_iddoes not appear inusershave no signup record to match and must be ignored. - Zero when nobody qualifies: Return
0(as a single row with columnusers_with_eventin SQL, or as a plainintin Python).
In the Python judge,
usersrows begin with[user_id, signup_date](sometimes followed by a thirdplan_typeelement that we do not need),eventsrows are[user_id, event_ts], and timestamps can arrive as'YYYY-MM-DD','YYYY-MM-DD HH:MM:SS', or'YYYY-MM-DDTHH:MM:SS'.- Inclusive comparison (
Write the PostgreSQL query first
In SQL, an inner join (
JOIN) keeps only(user, event)pairs that match onuser_idand satisfye.event_ts >= u.signup_date. Wrappingu.user_idinCOUNT(DISTINCT ...)collapses multiple qualifying events for the same user down to1:-- Aggregate without GROUP BY always returns 1 row (0 when no rows match). SELECT COUNT(DISTINCT u.user_id) AS users_with_event FROM users AS u -- INNER JOIN automatically drops users with no qualifying event and orphan events not in users. JOIN events AS e ON e.user_id = u.user_id AND e.event_ts >= u.signup_date;Notice why there is no
GROUP BY: a top-levelCOUNT(...)with noGROUP BYis guaranteed to return one row, andCOUNTover an empty result set returns0(unlikeSUM, which would returnNULL).Why nested loops are too slow, and how a lookup dictionary fixes it
A literal Python translation uses two nested loops: for every row in
users, loop through every row ineventsand testuser[0] == event[0] and event_ts >= signup_ts. With100,000users and1,000,000events, that executes10^11comparisons (O(U * E)), spending almost all of its time comparing an event with the wrong users!Instead, we build a dictionary
earliest_signup_by_user(user_id -> datetime) in oneO(U)pass overusers. Then each event ineventslooks up its ownuser_idinO(1)average time, cutting total runtime toO(U + E).What if the same
user_idappears in two rows ofuserswith two different signup timestamps (say2024-01-10and2024-01-01)? In the SQLJOIN, an event at2024-01-05matches the2024-01-01row and qualifies the user. In general, an event is>=at least one of a user's signups if and only if it is>=their earliest signup—so storing the minimumsignup_tsper user reproduces the SQL join identically!Why we must parse timestamps instead of comparing strings
It is tempting to compare timestamp strings directly with
event_str >= signup_str, especially since ISO dates put year, month, and day in order. When formats are mixed, however, plain text comparison silently gets the wrong answer for two reasons:Trap 1 — Bare date vs full midnight timestamp (same instant in time!): Text comparison: '2024-03-01' < '2024-03-01T00:00:00' (shorter string loses!) True time order: 2024-03-01 00:00:00 == 2024-03-01 00:00:00 (should qualify on >=) Trap 2 — Space (' ', ASCII 32) vs 'T' (ASCII 84) at index 10: Text comparison: '2024-03-01 10:00:00' < '2024-03-01T09:00:00' (' ' < 'T'!) True time order: 10:00 AM is 1 hour AFTER 9:00 AM!Parsing every string with
datetime.fromisoformat(str(value))solves both traps cleanly: it accepts both' 'and'T'separators and treats a bare'YYYY-MM-DD'date as midnight (00:00:00).from datetime import datetime def parse_timestamp(value: str) -> datetime: """Parse 'YYYY-MM-DD', 'YYYY-MM-DD HH:MM:SS', or 'YYYY-MM-DDTHH:MM:SS' into a datetime.""" # Bare dates like '2024-01-03' parse as midnight 00:00:00, matching PostgreSQL DATE -> TIMESTAMP coercion. return datetime.fromisoformat(str(value))Phase 1: Build the earliest-signup lookup dictionary
We scan
usersonce, reading onlyrow[0](user_id) androw[1](signup_date) so rows with or withoutplan_typeboth work. Any row whereuser_idorsignup_dateisNoneis skipped—just like SQLNULL, which never satisfies=or>=.from typing import Any, Dict, List from datetime import datetime def build_earliest_signups(users: List[List[str]]) -> Dict[Any, datetime]: """Map each valid user_id to their earliest signup datetime.""" # earliest_signup_by_user: maps user_id -> earliest signup datetime, e.g. {1: datetime(2024, 1, 1, 10, 0)}. earliest_signup_by_user: Dict[Any, datetime] = {} for row in users: user_id = row[0] raw_signup = row[1] # In SQL, NULL = x and y >= NULL evaluate to UNKNOWN, so missing IDs or signups can never join. if user_id is None or raw_signup is None: continue signup_ts = parse_timestamp(raw_signup) # If a user appears in multiple rows, an event >= ANY signup is equivalent to event >= EARLIEST signup. if user_id not in earliest_signup_by_user or signup_ts < earliest_signup_by_user[user_id]: earliest_signup_by_user[user_id] = signup_ts return earliest_signup_by_userPhase 2: Scan events once and collect distinct active users
Next we scan
eventsonce. Ifuser_idis missing fromearliest_signup_by_user(which covers bothNoneuser IDs and orphanuser_ids not inusers) orraw_event_tsisNone, we skip the event immediately before parsing. Wheneverevent_ts >= earliest_signup_by_user[user_id], we adduser_idto the setactive_users, which deduplicates repeated events automatically.from typing import Any, List, Set def count_users_with_event(users: List[List[str]], events: List[List[str]]) -> int: earliest_signup_by_user = build_earliest_signups(users) active_users: Set[Any] = set() for row in events: user_id = row[0] raw_event_ts = row[1] if user_id not in earliest_signup_by_user or raw_event_ts is None: continue event_ts = parse_timestamp(raw_event_ts) if event_ts >= earliest_signup_by_user[user_id]: active_users.add(user_id) return len(active_users)Trace Example 1 step by step
Let us trace Example 1: -
users = [[10, '2025-03-10 14:00:00', 'starter'], [20, '2025-03-12T08:30:00', 'pro'], [30, '2025-03-15', 'starter'], [40, '2025-03-18 09:00:00', 'team']]- Phase 1 buildsearliest_signup_by_user: -10 -> 2025-03-10 14:00:00-20 -> 2025-03-12 08:30:00-30 -> 2025-03-15 00:00:00(bare date parsed as midnight) -40 -> 2025-03-18 09:00:00Now Phase 2 scans
events:Event row Signup lookup event_ts >= signup_ts? active_users ---------------------------------------------------------------------------------------------- [10, '2025-03-10 14:00:00'] 2025-03-10 14:00:00 Yes (exact tie counts) {10} [10, '2025-03-11 09:15:00'] 2025-03-10 14:00:00 Yes (next day; already) {10} [20, '2025-03-12T08:29:59'] 2025-03-12 08:30:00 No (1s before signup) {10} [30, '2025-03-15 00:00:00'] 2025-03-15 00:00:00 Yes (midnight tie counts) {10, 30} [99, '2025-03-20 12:00:00'] not in dictionary Skipped (unknown user) {10, 30}Account
40had no events, solen(active_users)returns2.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from datetime import datetime def parse_timestamp(value: str) -> datetime: """Parse 'YYYY-MM-DD', 'YYYY-MM-DD HH:MM:SS', or 'YYYY-MM-DDTHH:MM:SS' into a datetime.""" # Bare dates like '2024-01-03' parse as midnight 00:00:00, matching PostgreSQL DATE -> TIMESTAMP coercion. return datetime.fromisoformat(str(value)) def build_earliest_signups(users: List[List[str]]) -> Dict[Any, datetime]: """Map each valid user_id to their earliest signup datetime.""" # earliest_signup_by_user: maps user_id -> earliest signup datetime, e.g. {1: datetime(2024, 1, 1, 10, 0)}. earliest_signup_by_user: Dict[Any, datetime] = {} for row in users: user_id = row[0] raw_signup = row[1] # In SQL, NULL = x and y >= NULL evaluate to UNKNOWN, so missing IDs or signups can never join. if user_id is None or raw_signup is None: continue signup_ts = parse_timestamp(raw_signup) # If a user appears in multiple rows, an event >= ANY signup is equivalent to event >= EARLIEST signup. if user_id not in earliest_signup_by_user or signup_ts < earliest_signup_by_user[user_id]: earliest_signup_by_user[user_id] = signup_ts return earliest_signup_by_user def count_users_with_event(users: List[List[str]], events: List[List[str]]) -> int: # Phase 1: Build an O(1)-lookup dictionary of each user's earliest signup timestamp. earliest_signup_by_user = build_earliest_signups(users) # Phase 2: Scan events once and collect distinct qualifying user_ids in a set. # active_users: set of distinct user_ids with at least one event_ts >= signup_date, e.g. {1, "u3"}. active_users: Set[Any] = set() for row in events: user_id = row[0] raw_event_ts = row[1] # Ignore orphan events (user_id not in users) and events with NULL timestamps. if user_id not in earliest_signup_by_user or raw_event_ts is None: continue event_ts = parse_timestamp(raw_event_ts) # Inclusive boundary (>=): an event at the exact signup second qualifies. if event_ts >= earliest_signup_by_user[user_id]: active_users.add(user_id) return len(active_users)✅ Submit now — all tests should pass.
Intuition & how it works
Think of users as a conference registration desk and events as a stream of room-entry badge scans. First, you copy every registered attendee's badge ID and check-in time onto an instant-lookup roster (earliest_signup_by_user, a hash dictionary). Next, you walk through the badge scans one by one: if a scan belongs to a registered badge ID and happened at or after their check-in time (>=), you toss that badge ID into a "verified active" bucket that ignores duplicates (a Python set, or COUNT(DISTINCT u.user_id) in SQL), and count how many unique IDs are in the bucket at the end.
A naive nested-loop approach compares every user row with every event row in O(U * E) time, wasting billions of checks pairing events with unrelated users. Another tempting shortcut—comparing raw timestamp strings without parsing—quietly fails whenever date formats mix spaces, 'T' separators, and bare 'YYYY-MM-DD' dates, because ASCII ' ' (32) sorts before 'T' (84), making '2024-03-01 10:00:00' compare as less than '2024-03-01T09:00:00'. Parsing into datetime objects and indexing signups by user_id makes every lookup fast and exact.
Walk through Example 1 step by step:
- Build roster: Account 10 -> 2025-03-10 14:00:00, Account 20 -> 2025-03-12 08:30:00, Account 30 -> 2025-03-15 00:00:00, Account 40 -> 2025-03-18 09:00:00.
- Scan events: [10, '2025-03-10 14:00:00'] ties Account 10's registration so active_users becomes {10}; [10, '2025-03-11 09:15:00'] also qualifies and keeps active_users at {10}; [20, '2025-03-12T08:29:59'] is 1 second before Account 20's registration so it fails; [30, '2025-03-15 00:00:00'] ties Account 30's midnight registration so active_users becomes {10, 30}; [99, '2025-03-20 12:00:00'] is absent from the roster so it is skipped.
- Final count: len({10, 30}) = 2.
Complexity
Let U be the number of rows in users and E be the number of rows in events.
- Time:
O(U + E)because we scan theUuser rows once to populateearliest_signup_by_userand then scan theEevent rows once, doing anO(1)average-time dictionary lookup and one timestamp parse per matching event. - Space:
O(U)because both theearliest_signup_by_userdictionary and theactive_usersset hold at most one entry per distinct user inusers, regardless of how largeeventsgrows. - SQL scaling: PostgreSQL typically executes
users JOIN events ON e.user_id = u.user_idas a hash join (hashing the smalleruserstable in memory and streamingeventspast it inO(U + E)time). If you filter to a small subset of users, a composite B-tree index onevents(user_id, event_ts)lets the database jump straight to each user's post-signup events without scanning the wholeeventstable.
Edge cases
- Event at the exact signup instant: Qualifies because the comparison
event_ts >= signup_dateis inclusive (>=). - Bare date strings (
'2024-01-03'): Treated as midnight00:00:00of that calendar day, matching how SQL compares aDATEagainst aTIMESTAMP. - Orphan events (
user_idmissing fromusers): Ignored by both SQLINNER JOINanduser_id not in earliest_signup_by_user. - Empty
usersoreventstable: Returns0(and in SQL,SELECT COUNT(...)withoutGROUP BYstill outputs a single row containing0). - Missing (
None/NULL) IDs or timestamps: In SQL's three-valued logic,NULL = xandx >= NULLevaluate toUNKNOWN, so rows withNonenever match or count. - Duplicate
user_idrows inusers: Keeping the earliest signup timestamp per user ensures an event qualifies whenever it is>=at least one of that user's signup rows, matching SQLJOIN+COUNT(DISTINCT u.user_id).
Common mistakes
- Using
COUNT(*)instead ofCOUNT(DISTINCT u.user_id): Counts the total number of qualifying events rather than distinct users. - Using strict
>instead of>=: Drops users whose only activity happened at the exact second of signup (such as Account30in Example 1). - Using
LEFT JOINand countingCOUNT(DISTINCT u.user_id): Because every row fromuserssurvives aLEFT JOIN, countingu.user_idcounts all users in the table rather than active ones (with aLEFT JOIN, you would have to counte.user_id). - Adding
GROUP BY u.user_id: Produces one row per user instead of a single summary row withusers_with_event. - Comparing raw timestamp strings in Python: Fails whenever
' 'and'T'separators or bare dates ('YYYY-MM-DD') are mixed together.
Follow-up questions
- How would you restrict the count to users who logged activity during a seven-day window [signup_date, signup_date + 7 days)? In SQL, add
AND e.event_ts < u.signup_date + INTERVAL '7 days'to theJOINcondition. In Python, checksignup_ts <= event_ts < signup_ts + timedelta(days=7)—and note that if a singleuser_idcan appear in multipleusersrows with different registration dates, you must store all registration timestamps for that user rather than only the earliest one, since an event 20 days after an initial signup could still fall inside the 7-day window of a later signup row. - If we want a per-tier breakdown across every plan_type—including tiers where zero users were active—what changes in the query? Replace the
INNER JOINwithFROM users u LEFT JOIN events e ON e.user_id = u.user_id AND e.event_ts >= u.signup_date, addGROUP BY u.plan_type, and selectu.plan_type, COUNT(DISTINCT e.user_id) AS users_with_event. Countinge.user_idrather thanu.user_idskips theNULLevent columns of inactive users while keeping zero-activity tiers in the output with a count of0. - When the events log holds billions of records for a relatively small user table, how can you speed up the database execution? Observe that a user has some event
>= signup_dateif and only if their latest event (MAX(event_ts)) satisfiesMAX(event_ts) >= signup_date. You can either pre-aggregateSELECT user_id, MAX(event_ts) AS latest_ts FROM events GROUP BY user_iddown to one row per user before joining, or writeWHERE EXISTS (SELECT 1 FROM events e WHERE e.user_id = u.user_id AND e.event_ts >= u.signup_date)backed by a composite B-tree index onevents(user_id, event_ts)so PostgreSQL stops probing after the first matching event per user.
Follow-up questions
- How would you restrict the count to users who logged activity during a seven-day window [signup_date, signup_date + 7 days)?
- If we want a per-tier breakdown across every plan_type—including tiers where zero users were active—what changes in the query?
- When the events log holds billions of records for a relatively small user table, how can you speed up the database execution?
Similar questions
- Seven-Day Retention Rates by Weekly Cohort
- Seven-Day User Retention Across Subscription Tiers
- Day-Seven Calendar Retention Count
- Hierarchical Event Counts by Attribute Order
- Exact Sum of Decimal Strings
- Evaluating Predictive Signals for Customer Retention
More Mixpanel interview questions
- Seven-Day Retention Rates by Weekly Cohort Medium
- Seven-Day User Retention Across Subscription Tiers Medium
- Day-Seven Calendar Retention Count Medium Pro
- Evaluating Predictive Signals for Customer Retention Medium Pro
- Hierarchical Event Counts by Attribute Order Medium Pro
- Exact Sum of Decimal Strings Medium Pro