Rolling Seven-Day Unique Viewers per Creator in Plain Python
Last updated: November 29, 2026
Quick Overview
Given view events of (creator_id, viewer_id, date), compute for each creator and every calendar day the number of distinct viewers over the trailing seven days, in Python without pandas, efficiently enough for creators with millions of views.
Meta
November 29, 20260
0
0 solved
Given view events of (creator_id, viewer_id, date), compute for each creator and every calendar day the number of distinct viewers over the trailing seven days, in Python without pandas, efficiently enough for creators with millions of views.
Creator dashboards on Facebook and Instagram show rolling unique audience, and distinct counts are the classic case where SQL window functions fall short (COUNT DISTINCT is not allowed in a window in most engines). The interviewer wants a sliding-window algorithm that adds the entering day and removes the leaving day instead of recomputing each window.
What the Interviewer Expects
- Explains why COUNT(DISTINCT) over a sliding window is not directly available and why summing daily uniques is wrong
- Deduplicates viewers per creator per day
- Maintains a per-viewer counter of window days so removal is correct when a viewer appears on several days
- Outputs every calendar day, including days with no views
- States complexity and verifies against a brute force
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 produce the same metric at Meta scale with approximate sketches such as HyperLogLog?
- How would you get it in pandas, and what is the memory cost of the explode approach?
- How would you extend it to 28-day and 7-day windows in one pass?
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: an iterable of (creator_id, viewer_id, ds). Repeat views by the same viewer on one day count once. Window for day d covers . Output days run from the creator's first view day to the...
Approach
Bucket views into creator -> day -> set(viewers). For each creator, walk days in order with a Counter that maps viewer to the number of window days they appear on. On each step, add the entering d...