Owner and Guest Document Edit Rates
Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen
Problem Statement
Write a SQL query that computes daily owner and anonymous-guest contribution rates across active non-private documents in a collaborative workspace.
Apply the following rules for each calendar day (YYYY-MM-DD):
- Eligible documents only: Consider only edits whose
doc_idappears indocumentswithis_privatenot equal toTRUE(FalseorNULL). Ignore edits referencing private documents ordoc_idvalues missing fromdocuments. - Document-level daily denominator: On each calendar day that has at least one eligible edit, the denominator is the count of distinct active non-private documents edited on that day (including documents edited only by signed-in non-owner collaborators). Multiple edits to the same document on the same day — even within the exact same second — count that document once.
- Owner and guest percentages (
0–100scale):percent_owner_edits: percentage of active non-private documents on that day that received at least one edit whereedits.user_id = documents.owner_id, rounded to4decimal places.percent_guest_edits: percentage of active non-private documents on that day that received at least one edit whereedits.user_id IS NULL(an anonymous guest), rounded to4decimal places.- Because the same document can be edited by both its owner and an anonymous guest on the same day, a single document may contribute to both numerators (so the two percentages can sum to more than
100.0).
Return columns date, percent_owner_edits, and percent_guest_edits for every calendar day with at least one eligible edit, in any row order.
Input Schema
edits
| Column | Type | Description |
|---|---|---|
user_id |
INTEGER |
Identifier of the editing user, or NULL when edited by an anonymous guest. |
doc_id |
VARCHAR |
Identifier of the edited document. |
timestamp |
TIMESTAMP |
ISO-formatted timestamp of the edit (YYYY-MM-DD HH:MM:SS or YYYY-MM-DDTHH:MM:SS). |
edit_size_bytes |
INTEGER |
Byte size of the edit payload. |
documents
| Column | Type | Description |
|---|---|---|
doc_id |
VARCHAR |
Unique identifier of the document. |
owner_id |
INTEGER |
Identifier of the user who owns the document. |
created_at |
TIMESTAMP |
Creation timestamp of the document. |
is_private |
BOOLEAN |
TRUE if the document is private (excluded from reporting), FALSE otherwise. |
Examples
Example 1
Input:
documents
| doc_id | owner_id | created_at | is_private |
|---|---|---|---|
| D1 | 301 | 2024-08-15 09:00:00 | False |
| D2 | 302 | 2024-08-20 14:30:00 | False |
| D3 | 303 | 2024-08-25 11:00:00 | False |
| D4 | 304 | 2024-09-01 08:00:00 | True |
edits
| user_id | doc_id | timestamp | edit_size_bytes |
|---|---|---|---|
| 301 | D1 | 2024-09-10 09:15:00 | 120 |
| NULL | D1 | 2024-09-10 09:15:00 | 45 |
| NULL | D2 | 2024-09-10 14:20:00 | 80 |
| NULL | D2 | 2024-09-10 14:20:00 | 30 |
| 399 | D3 | 2024-09-10 16:45:00 | 210 |
| 304 | D4 | 2024-09-10 17:00:00 | 60 |
| 302 | D2 | 2024-09-11 10:05:00 | 95 |
| 303 | D3 | 2024-09-11 11:30:00 | 150 |
| NULL | D3 | 2024-09-11 15:00:00 | 40 |
Output:
| date | percent_owner_edits | percent_guest_edits |
|---|---|---|
| 2024-09-10 | 33.3333 | 66.6667 |
| 2024-09-11 | 100.0 | 50.0 |
Explanation:
- 2024-09-10: Private document D4 is excluded, leaving 3 active non-private documents (D1, D2, D3). D1 has both an owner edit (301) and a guest edit (NULL); D2 has two same-second guest edits (counted once); D3 has only a signed-in peer edit (399, counted in the denominator only). Owner rate: 100.0 * 1 / 3 = 33.3333; guest rate: 100.0 * 2 / 3 = 66.6667.
- 2024-09-11: 2 active non-private documents (D2, D3). Both are edited by their owners (2 / 2 = 100.0), and D3 is also edited by a guest (1 / 2 = 50.0).
Constraints
datemust be formatted as'YYYY-MM-DD'.percent_owner_editsandpercent_guest_editsare expressed on a0–100scale and rounded to4decimal places.- Days with zero edits to non-private documents present in
documentsmust not appear in the output. - Output rows may be returned in any order.
Step-by-step walkthrough
Understand the metric and its unit of counting
We have two tables from a collaborative document editor:
edits(user_id, doc_id, timestamp, edit_size_bytes): every edit event (user_idisNULLwhen the editor is an anonymous guest).documents(doc_id, owner_id, created_at, is_private): metadata for each document.
For each calendar day that has at least one edit to a non-private document in
documents, we must compute:percent_owner_edits: percentage of active public documents edited at least once by theirowner_idthat day.percent_guest_edits: percentage of active public documents edited at least once by an anonymous guest (user_id IS NULL) that day.
Notice that the unit of counting is distinct active public documents on that day, not raw edit rows — and there are three kinds of editors:
Three types of edits on a public document (owner_id = 301): 1. e.user_id = 301 -> Owner edit (enters denominator AND owner numerator) 2. e.user_id IS NULL -> Anonymous guest (enters denominator AND guest numerator) 3. e.user_id = 399 -> Signed-in peer (enters denominator ONLY — neither numerator!) Why we group by (day, doc_id) BEFORE computing percentages: Doc D1 edited 10 times by owner + Doc D2 edited 1 time by guest Wrong (edit-level): 10 / 11 = 90.91% owner, 1 / 11 = 9.09% guest Right (document-level): 1 / 2 = 50.00% owner, 1 / 2 = 50.00% guestAlso, because a single document can be edited by both its owner and a guest on the same day (like
D1on2024-09-10andD3on2024-09-11in Example 1), both metrics count that document, so the two percentages do not have to add up to100.0.Filter to known public documents and extract calendar dates
Before counting anything, we join
editstodocumentsto look upowner_idandis_private, and slice each timestamp to its calendar date:- Use an inner
JOIN, not aLEFT JOIN: Only documents present indocumentsand not private belong in the metric. If an edit references an unknowndoc_id(say'Z') and we used aLEFT JOIN,'Z'would survive withd.is_private = NULL, pass the privacy filter, and falsely inflate the denominator! (Even if you pre-filtereddocumentsto public rows first, aLEFT JOINfromeditswould keep private-document edits withNULLmetadata unless you immediately dropped unmatched rows — which is simply an innerJOIN.) WHERE d.is_private IS NOT TRUE: Drops rows whereis_privateis true (1), while safely keepingFalse(0) andNULL.date(e.timestamp): Extracts'YYYY-MM-DD'cleanly whethertimestampuses a space ('2023-03-02 08:15:00') or an ISO'T'separator ('2023-03-02T08:15:00').
FROM edits AS e JOIN documents AS d ON d.doc_id = e.doc_id WHERE d.is_private IS NOT TRUE- Use an inner
Collapse edits to one row per document per day
Next, we group the filtered edits by
(date(e.timestamp), e.doc_id)in a CTE calleddoc_days. Each group represents one public document that was active on one calendar day.Inside each
(day, doc_id)group, we compute two0/1flags usingMAX(CASE ...), which acts as "was there at least one edit of this kind?":MAX(CASE WHEN e.user_id = d.owner_id THEN 1 ELSE 0 END) AS has_owner_edit: evaluates to1if the owner edited the document at least once that day. Whene.user_idisNULL,NULL = d.owner_idisUNKNOWN, so theELSE 0branch safely yields0.MAX(CASE WHEN e.user_id IS NULL THEN 1 ELSE 0 END) AS has_guest_edit: evaluates to1if an anonymous guest edited the document at least once that day. Always writeIS NULL— writinge.user_id = NULLis never true in SQL!
Grouping by
(day, doc_id)also automatically handles duplicate timestamps: whether an owner saves 1 edit or 5 edits in the exact same second,MAX(...)still produces a single row withhas_owner_edit = 1.WITH doc_days AS ( -- Phase 1: Collapse all edits on the same (day, doc_id) into ONE row per -- active public document, with 0/1 flags for owner and guest activity. -- INNER JOIN drops edits whose doc_id is missing from documents, and -- d.is_private IS NOT TRUE excludes private documents before counting. SELECT date(e.timestamp) AS day, e.doc_id, MAX(CASE WHEN e.user_id = d.owner_id THEN 1 ELSE 0 END) AS has_owner_edit, MAX(CASE WHEN e.user_id IS NULL THEN 1 ELSE 0 END) AS has_guest_edit FROM edits AS e JOIN documents AS d ON d.doc_id = e.doc_id WHERE d.is_private IS NOT TRUE GROUP BY date(e.timestamp), e.doc_id )Roll up daily percentages
Now that
doc_daysholds exactly one row per active public document per day, the final daily summary is a clean secondGROUP BY day:COUNT(*)is the total number of distinct active public documents onday(including documents edited only by signed-in non-owner collaborators, where both flags are0).SUM(has_owner_edit)is how many of those documents had at least one owner edit.SUM(has_guest_edit)is how many of those documents had at least one guest edit.- Multiplying by
100.0(with a decimal point!) prevents integer division (100.0 * 1 / 3 = 33.3333..., whereas100 * 1 / 3truncates to33), andROUND(..., 4)rounds to 4 decimal places. Because a day only entersdoc_dayswhen at least one public document was edited,COUNT(*)is guaranteed to be at least1.
-- Phase 2: Roll up active public documents per calendar day. -- COUNT(*) counts every edited public document (including collaborator-only docs), -- and 100.0 forces floating-point division before rounding to 4 decimals. SELECT day AS date, ROUND(100.0 * SUM(has_owner_edit) / COUNT(*), 4) AS percent_owner_edits, ROUND(100.0 * SUM(has_guest_edit) / COUNT(*), 4) AS percent_guest_edits FROM doc_days GROUP BY day ORDER BY dayWalk through Example 1 across both days
Let's trace Example 1 (
D1owner301,D2owner302,D3owner303, and privateD4owner304):On '2024-09-10' (private doc 'D4' is dropped by WHERE d.is_private IS NOT TRUE): doc 'D1': owner 301 + guest NULL in same second -> has_owner_edit = 1, has_guest_edit = 1 doc 'D2': two guest NULL edits in same second -> has_owner_edit = 0, has_guest_edit = 1 doc 'D3': peer 399 edit (not owner, not NULL) -> has_owner_edit = 0, has_guest_edit = 0 (in denominator!) COUNT(*) = 3 active public docs: percent_owner_edits = ROUND(100.0 * 1 / 3, 4) = 33.3333 percent_guest_edits = ROUND(100.0 * 2 / 3, 4) = 66.6667 On '2024-09-11': doc 'D2': owner 302 edit -> has_owner_edit = 1, has_guest_edit = 0 doc 'D3': owner 303 edit + guest NULL edit -> has_owner_edit = 1, has_guest_edit = 1 COUNT(*) = 2 active public docs: percent_owner_edits = ROUND(100.0 * 2 / 2, 4) = 100.0 percent_guest_edits = ROUND(100.0 * 1 / 2, 4) = 50.0Complete SQL query
WITH doc_days AS ( -- Phase 1: Collapse all edits on the same (day, doc_id) into ONE row per -- active public document, with 0/1 flags for owner and guest activity. -- INNER JOIN drops edits whose doc_id is missing from documents, and -- d.is_private IS NOT TRUE excludes private documents before counting. SELECT date(e.timestamp) AS day, e.doc_id, MAX(CASE WHEN e.user_id = d.owner_id THEN 1 ELSE 0 END) AS has_owner_edit, MAX(CASE WHEN e.user_id IS NULL THEN 1 ELSE 0 END) AS has_guest_edit FROM edits AS e JOIN documents AS d ON d.doc_id = e.doc_id WHERE d.is_private IS NOT TRUE GROUP BY date(e.timestamp), e.doc_id ) -- Phase 2: Roll up active public documents per calendar day. -- COUNT(*) counts every edited public document (including collaborator-only docs), -- and 100.0 forces floating-point division before rounding to 4 decimals. SELECT day AS date, ROUND(100.0 * SUM(has_owner_edit) / COUNT(*), 4) AS percent_owner_edits, ROUND(100.0 * SUM(has_guest_edit) / COUNT(*), 4) AS percent_guest_edits FROM doc_days GROUP BY day ORDER BY day✅ Submit now — all tests should pass.
Intuition & how it works
Imagine walking through a shared workspace at the end of each day to inspect every public whiteboard that someone wrote on: rather than counting individual marker strokes, you keep one checklist line per active whiteboard and tick two independent boxes — "Did the board's owner write on it today?" and "Did an anonymous visitor write on it today?" In SQL, summarizing raw events at the entity-day level before computing daily averages is a two-stage aggregation, written cleanly with a common table expression, or CTE (a named temporary step introduced with WITH). We pair edits with documents using an inner join (a join that keeps only rows whose doc_id exists in both tables) and filter out private documents first so unknown and private boards never enter the checklist.
The naive one-step approach — dividing owner edit rows or guest edit rows by total edit rows per day — fails because the metric asks for the percentage of documents, not edits: one owner making 50 rapid edits to a single document would dominate the entire day, and on 2024-09-11 in Example 1 (3 total edits across 2 docs) row-level division would report 66.6667% / 33.3333% instead of 100.0% / 50.0%. Another common trap is pre-filtering edits to user_id = owner_id OR user_id IS NULL before grouping, which throws away public documents edited exclusively by signed-in teammates and artificially inflates both percentages.
Walk through 2024-09-10 in Example 1: public Document D1 (owner_id = 301) gets an edit from 301 and an edit from NULL; public Document D2 (owner_id = 302) gets two edits in the exact same second from NULL; public Document D3 (owner_id = 303) gets an edit from signed-in teammate 399; and private Document D4 (is_private = True) is excluded up front:
1. doc_days groups by (day, doc_id), collapsing D2's same-second edits into a single row and yielding 3 active-document rows: D1 -> (owner = 1, guest = 1), D2 -> (owner = 0, guest = 1), and D3 -> (owner = 0, guest = 0).
2. The outer query groups by day, counting COUNT(*) = 3 active public documents in the denominator.
3. Summing the flags gives percent_owner_edits = ROUND(100.0 * 1 / 3, 4) = 33.3333 and percent_guest_edits = ROUND(100.0 * 2 / 3, 4) = 66.6667.
Complexity
Let E be the number of rows in edits, D be the number of rows in documents, and K (K <= E) be the number of distinct (day, doc_id) pairs among public edits.
- Time:
O(E + D)average time with a hash join and hash aggregation, orO(E log D + E log E)when probing a B-tree index and sorting. Building a hash lookup table ondocuments(doc_id)takesO(D)work and probing it once per edit takesO(E)work; grouping those public edits intoK(day, doc_id)rows takesO(E)hash updates (orO(E log E)comparisons if sort-based), and the final daily roll-up scans only theKsummarized rows (plus an inexpensive sort over the number of distinct days forORDER BY day). - Space:
O(D + K), since the database holds at mostDdocument metadata records for the join andK(day, doc_id)flag rows indoc_days. - Indexes that help: A primary key or index on
documents(doc_id)accelerates the join lookup. Becausedate(e.timestamp)is a function call, storing or partitioningeditsby a precomputededit_datecolumn lets analytical engines prune date ranges and group without recomputingdate(...)on every row.
Edge cases
- Multiple edits on the same document in the same second: Collapsed into one
(day, doc_id)group byGROUP BY date(e.timestamp), e.doc_id, withMAX(...)keeping the flag at1. - Same document edited by both owner and guest: Both
has_owner_editandhas_guest_editequal1, so both percentages include it and their sum can exceed100.0(such as100.0 + 50.0 = 150.0on2024-09-11in Example 1, or up to200.0). - Documents edited only by signed-in non-owner collaborators: Remain in
doc_dayswith(0, 0), contributing1toCOUNT(*)in the denominator and0to both numerators. - Private documents and days with only private edits: Excluded by
WHERE d.is_private IS NOT TRUEbefore grouping, so private-only days emit no row. - Edits referencing a
doc_idabsent fromdocuments: Dropped immediately by the innerJOIN. - Documents with
owner_id IS NULL:e.user_id = NULLevaluates toUNKNOWNeven whene.user_idis alsoNULL, soELSE 0setshas_owner_edit = 0while guest edits still counthas_guest_edit = 1. - CSV boolean strings imported into SQLite: Raw CSV loaders sometimes import
'True'and'False'as text strings rather than1and0; in SQLite'True' IS NOT TRUEis true, so CSV ingestion scripts should cast booleans (LOWER(is_private) IN ('true', '1')) on load. - Midnight boundaries and ISO
'T'timestamps:date('2023-03-01 23:59:59')(2023-03-01) anddate('2023-03-02T00:00:00')(2023-03-02) cleanly land on separate days.
Common mistakes
- Aggregating directly at the edit level without
doc_days: Weights documents by how many times someone saved rather than counting distinct active documents. - Filtering to
e.user_id = d.owner_id OR e.user_id IS NULLbefore grouping: Drops collaborator-only documents fromCOUNT(*)and inflates both percentages. - Using
LEFT JOIN documents: Keeps edits to unknowndoc_ids withd.is_private = NULL, which passesIS NOT TRUEand pollutes the denominator. - Writing
e.user_id = NULLinstead ofe.user_id IS NULL: Comparisons with= NULLnever evaluate to true in SQL, forcingpercent_guest_editsto0.0on every day. - Defining guests as
e.user_id <> d.owner_id: Miscounts signed-in collaborators as guests while missing real guests (becauseNULL <> owner_idisUNKNOWN, not true!). - Grouping by raw
e.timestampinstead ofdate(e.timestamp): Produces one output row per timestamp second instead of per calendar day. - Integer division (
100 * SUM(...) / COUNT(*)): Truncates100 * 1 / 3to33instead of33.3333in SQLite and PostgreSQL.
Follow-up questions
- How would you include quiet calendar days or unedited public documents so the daily time series has no missing dates? First clarify which gap the stakeholder wants filled: if they want one row for every calendar day even when zero public documents were edited site-wide, generate a continuous calendar with a recursive CTE (a
WITH RECURSIVEquery that steps+1 dayfrom the minimum to the maximum date),LEFT JOIN doc_daysonto it, and divide byNULLIF(COUNT(dd.doc_id), 0)so quiet days appear withNULLrates and an explicitactive_docs = 0column rather than a misleading0%. If instead they want unedited public documents included in every day's denominator ("share of all existing public documents touched by an owner today"), cross-join the calendar spine with publicdocumentswheredate(created_at) <= dayandLEFT JOIN doc_daysso untouched documents contribute0to the numerators and1to the denominator. - How would you scale this pipeline in a data warehouse once raw edit logs reach billions of events? Use table partitioning (splitting
editsphysically on disk byedit_date) and build an incremental daily summary table(day, doc_id, has_owner_edit, has_guest_edit)so each night's job scans only the new day's raw edits rather than all historical billions of rows. Store data in columnar storage (saving each column separately so the engine reads onlyuser_id,doc_id, andtimestampwhile skippingedit_size_bytes), filteris_private IS NOT TRUEearly, and use a broadcast join (sending the much smaller publicdocumentslookup table to every worker node so massiveeditspartitions never shuffle across the network). Recompute and overwrite the last 2–3 date partitions on each run so late-arriving events are captured and reruns stay idempotent (safe to run repeatedly with identical results). - What signals could link logged-out guest edits back to existing accounts, and why is IP matching alone unreliable? Log a persistent first-party browser cookie or device ID alongside every edit event: if that same cookie ID authenticates with a non-null
user_idin an earlier or later session, deterministic identity stitching can link the logged-out edit back to that account (and check whether it actually belongs toowner_idor a collaborator!). Avoid linking on IP address alone because corporate offices, universities, VPNs, and cellular carriers share one IP across many people while mobile users switch IPs constantly; use IP only as a weak supporting signal combined with user-agent string, document access token, and tight time proximity. Validate precision against ground-truth sessions where an anonymous editor logs in mid-session, report both raw and stitched rates, and enforce privacy and cookie-consent rules before linking identifiers.
Follow-up questions
- How would you include quiet calendar days or unedited public documents so the daily time series has no missing dates?
- How would you scale this pipeline in a data warehouse once raw edit logs reach billions of events?
- What signals could link logged-out guest edits back to existing accounts, and why is IP matching alone unreliable?
Similar questions
- Workspace Document Collaboration Metrics
- Workspace Document Collaboration Metrics
- Multi-User Calendar and Event Reminder Platform
- Reversible Text Buffer with Undo and Redo
- Hierarchical Task Checklist Service
- Data Engineering Ownership, Impact, and Partner Collaboration
More Notion interview questions
- Workspace Document Collaboration Metrics Easy
- Workspace Document Collaboration Metrics Medium
- Multi-User Calendar and Event Reminder Platform Medium Pro
- Hierarchical Task Checklist Service Medium Pro
- Reversible Text Buffer with Undo and Redo Medium Pro
- Data Engineering Ownership, Impact, and Partner Collaboration Medium Pro
- Top-K Frequent Error Codes in a Time Interval Medium Pro
- Collapsible JSON Tree Component in React Medium Pro