Compute Day-N Retention From Raw Login Events in Plain Python
Last updated: November 29, 2026
Quick Overview
Write a Python function that takes a list of (user_id, date) login events and a list of day offsets, and returns for each first-login cohort date the fraction of users who logged in exactly N days later, marking offsets not yet observable as None.
Meta
November 29, 20260
0
0 solved
Write a Python function that takes a list of (user_id, date) login events and a list of day offsets, and returns for each first-login cohort date the fraction of users who logged in exactly N days later, marking offsets not yet observable as None.
Meta product and infra engineers working on growth tooling are sometimes asked to implement metrics logic directly in Python without pandas. The interviewer checks clean use of dicts and sets, correct cohort assignment, and awareness of incomplete data.
What the Interviewer Expects
- Group events into a set of days per user
- Assign each user to the cohort of their first login
- Use set membership for O(1) lookups of the target day
- Handle duplicate events
- Return None for immature offsets when an as-of date is given
Key Topics to Cover
How to Approach This
- Clarify the schema and expected output format before writing queries.
- Use CTEs (WITH clauses) to break complex queries into readable steps.
- Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
- Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
- For pandas, prefer vectorized operations over row-by-row iteration.
Possible Follow-up Questions
- How would you stream this if events do not fit in memory?
- How would you change it to unbounded retention?
- How would you parallelize across many machines?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice SQL ProblemsSample Answer
Clarify the Data
Input is an unsorted list of (user_id, datetime.date) with possible duplicates; offsets like [1, 7, 30]; optional as_of date marking the last day of data. Output: {cohort_date: {n: rate}}....
Approach
First pass: build user -> set(days). The cohort is min(days). Second pass: group users by cohort. For each cohort and offset compute target = cohort + n days and count users whose set contains i...