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 containing user_id, signup_date, and optionally plan_type.
  • events: activity rows containing user_id and event_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_id and require event_ts >= signup_date (an event at the exact registration second qualifies; an event even one second earlier does not).
  • Count each qualifying user_id once regardless of how many post-signup events they logged.
  • Ignore events whose user_id does not appear in users, and ignore rows where user_id, signup_date, or event_ts is None (NULL).
  • If the same user_id appears in multiple users rows, an event at or after any valid signup_date for that user qualifies them.
  • Return 0 when 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 midnight 00:00:00), or None (NULL).
  • Each users row starts with [user_id, signup_date] (with an optional third element plan_type); each events row is [user_id, event_ts].
  • users and events can be empty, contain duplicate rows, or contain None (NULL) values.

Step-by-step walkthrough

  1. Understand the tables, rules, and input shapes

    We are given two tables—users(user_id, signup_date, plan_type) and events(user_id, event_ts)—and asked to count how many distinct users have at least one event at or after their signup_date.

    Keep four rules front and center:

    • Inclusive comparison (>=): An event at the exact instant of signup_date qualifies; an event even 1 second before signup_date does not.
    • Distinct users, not events: A user with ten qualifying events adds 1 to the total, not 10.
    • Registered users only: Events whose user_id does not appear in users have no signup record to match and must be ignored.
    • Zero when nobody qualifies: Return 0 (as a single row with column users_with_event in SQL, or as a plain int in Python).

    In the Python judge, users rows begin with [user_id, signup_date] (sometimes followed by a third plan_type element that we do not need), events rows 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'.

  2. Write the PostgreSQL query first

    In SQL, an inner join (JOIN) keeps only (user, event) pairs that match on user_id and satisfy e.event_ts >= u.signup_date. Wrapping u.user_id in COUNT(DISTINCT ...) collapses multiple qualifying events for the same user down to 1:

    -- 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-level COUNT(...) with no GROUP BY is guaranteed to return one row, and COUNT over an empty result set returns 0 (unlike SUM, which would return NULL).

  3. 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 in events and test user[0] == event[0] and event_ts >= signup_ts. With 100,000 users and 1,000,000 events, that executes 10^11 comparisons (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 one O(U) pass over users. Then each event in events looks up its own user_id in O(1) average time, cutting total runtime to O(U + E).

    What if the same user_id appears in two rows of users with two different signup timestamps (say 2024-01-10 and 2024-01-01)? In the SQL JOIN, an event at 2024-01-05 matches the 2024-01-01 row 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 minimum signup_ts per user reproduces the SQL join identically!

  4. 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))
    
  5. Phase 1: Build the earliest-signup lookup dictionary

    We scan users once, reading only row[0] (user_id) and row[1] (signup_date) so rows with or without plan_type both work. Any row where user_id or signup_date is None is skipped—just like SQL NULL, 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_user
    
  6. Phase 2: Scan events once and collect distinct active users

    Next we scan events once. If user_id is missing from earliest_signup_by_user (which covers both None user IDs and orphan user_ids not in users) or raw_event_ts is None, we skip the event immediately before parsing. Whenever event_ts >= earliest_signup_by_user[user_id], we add user_id to the set active_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)
    
  7. 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 builds earliest_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:00

    Now 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 40 had no events, so len(active_users) returns 2.

  8. 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 the U user rows once to populate earliest_signup_by_user and then scan the E event rows once, doing an O(1) average-time dictionary lookup and one timestamp parse per matching event.
  • Space: O(U) because both the earliest_signup_by_user dictionary and the active_users set hold at most one entry per distinct user in users, regardless of how large events grows.
  • SQL scaling: PostgreSQL typically executes users JOIN events ON e.user_id = u.user_id as a hash join (hashing the smaller users table in memory and streaming events past it in O(U + E) time). If you filter to a small subset of users, a composite B-tree index on events(user_id, event_ts) lets the database jump straight to each user's post-signup events without scanning the whole events table.

Edge cases

  • Event at the exact signup instant: Qualifies because the comparison event_ts >= signup_date is inclusive (>=).
  • Bare date strings ('2024-01-03'): Treated as midnight 00:00:00 of that calendar day, matching how SQL compares a DATE against a TIMESTAMP.
  • Orphan events (user_id missing from users): Ignored by both SQL INNER JOIN and user_id not in earliest_signup_by_user.
  • Empty users or events table: Returns 0 (and in SQL, SELECT COUNT(...) without GROUP BY still outputs a single row containing 0).
  • Missing (None / NULL) IDs or timestamps: In SQL's three-valued logic, NULL = x and x >= NULL evaluate to UNKNOWN, so rows with None never match or count.
  • Duplicate user_id rows in users: Keeping the earliest signup timestamp per user ensures an event qualifies whenever it is >= at least one of that user's signup rows, matching SQL JOIN + COUNT(DISTINCT u.user_id).

Common mistakes

  • Using COUNT(*) instead of COUNT(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 Account 30 in Example 1).
  • Using LEFT JOIN and counting COUNT(DISTINCT u.user_id): Because every row from users survives a LEFT JOIN, counting u.user_id counts all users in the table rather than active ones (with a LEFT JOIN, you would have to count e.user_id).
  • Adding GROUP BY u.user_id: Produces one row per user instead of a single summary row with users_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 the JOIN condition. In Python, check signup_ts <= event_ts < signup_ts + timedelta(days=7)—and note that if a single user_id can appear in multiple users rows 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 JOIN with FROM users u LEFT JOIN events e ON e.user_id = u.user_id AND e.event_ts >= u.signup_date, add GROUP BY u.plan_type, and select u.plan_type, COUNT(DISTINCT e.user_id) AS users_with_event. Counting e.user_id rather than u.user_id skips the NULL event columns of inactive users while keeping zero-activity tiers in the output with a count of 0.
  • 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_date if and only if their latest event (MAX(event_ts)) satisfies MAX(event_ts) >= signup_date. You can either pre-aggregate SELECT user_id, MAX(event_ts) AS latest_ts FROM events GROUP BY user_id down to one row per user before joining, or write WHERE 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 on events(user_id, event_ts) so PostgreSQL stops probing after the first matching event per user.

Follow-up questions

Similar questions

More Mixpanel interview questions

All 7 Mixpanel questions →