Calculate Contributor Type Distribution from Activity Logs
SQL & DataModel answerLast updated
Clean and aggregate edit logs to compute daily percentages of documents edited by owners versus anonymous users.
Problem
You're building analytics for a collaborative editing platform. Given two datasets containing edit activity and document metadata, compute daily statistics about who is making changes.
Dataset 1: edits.csv
Contains every edit made to any document with these fields:
user_id: identifier of the editor (may be null for anonymous sessions)doc_id: identifier of the documenttimestamp: when the edit occurred (ISO 8601 format)edit_size_bytes: size of the change
Dataset 2: documents.csv
Contains document metadata:
doc_id: identifier of the documentowner_id: identifier of the user who created this documentcreated_at: creation timestampis_private: whether the document is private
Your Task
Produce a summary table showing, for each date, what percentage of actively-edited documents received at least one edit from their owner, and what percentage received at least one edit from an anonymous user.
Return these columns:
date: the calendar daypercent_owner_edits: percentage of documents edited by their owner that daypercent_guest_edits: percentage of documents edited by anonymous users that day
Rules
- Only count documents where
is_privateis false - An "owner edit" occurs when
user_idmatches the document'sowner_id - A "guest edit" occurs when
user_idis null - Multiple edits to the same document on the same day count as one document
- A document can contribute to both percentages if it has both types of edits
- Extract the date from timestamps properly (handle time zones if present)
Example
edits.csv:
user_id,doc_id,timestamp,edit_size_bytes
101,A,2023-01-01T10:00:00,50
,A,2023-01-01T11:00:00,20
documents.csv:
doc_id,owner_id,created_at,is_private
A,101,2023-01-01,false
Expected output:
date,percent_owner_edits,percent_guest_edits
2023-01-01,100.0,100.0
Document A had one edit by its owner (user 101) and one by an anonymous user, so it appears in both numerators. Since it's the only active document that day, both percentages are 100%.
Hints
Hint 1
Think about the unit of measurement: you're counting documents, not individual edits
Hint 2
Use a two-stage aggregation: first collapse to (date, document) pairs, then to dates
Hint 3
A logged-in user who isn't the owner contributes to the denominator but not to either numerator
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Calculate Contributor Type Distribution
Understanding the Metric
Before writing any code, clarify what we're measuring:
Unit of analysis: Each (date, document) pair counts once. We're not counting raw edits.
Denominator: Public documents that had at least one edit on a given day.
Numerators:
- Owner edits: documents where at least one edit came from a user whose ID matches
owner_id - Guest edits: documents where at least one edit had a null
user_id - Non-owner collaborators: logged-in users who aren't the owner count toward the denominator but neither numerator
Important implication: The two percentages don't necessarily sum to 100%. A document edited by both its owner and a guest contributes to both numerators (appears in both percentages). A document edited only by a non-owner collaborator contributes only to the denominator (appears in neither percentage).
Approach
The solution requires a two-level aggregation pattern:
-
Data preparation:
- Parse timestamps to extract dates
- Normalize ID fields (handle nulls spelled as "NULL", "NaN", etc.)
- Join edits with document metadata
- Filter to only public documents
-
First aggregation (per document per day):
- Group by (date, doc_id)
- Compute two boolean flags:
has_owner_editandhas_guest_edit - Use logical OR (
ANYin SQL,any()in pandas) to check if at least one qualifying edit exists
-
Second aggregation (per day):
- Group by date
- Count total documents (denominator)
- Sum the boolean flags (numerators)
- Calculate percentages
Why This Works
The two-stage aggregation avoids a common pitfall: if you try to aggregate directly from edits to dates, you'll incorrectly weight documents by their edit counts.
The inner aggregation with ANY/any() elegantly handles duplicates and repeated edits—whether there's one owner edit or twenty, the document still just gets marked true for has_owner_edit.
Edge Cases to Handle
- ID type mismatches:
user_idmay be float (101.0) due to NaNs whileowner_idis integer - Null representations: "", "NULL", "None" in text all mean anonymous
- Boolean formats: "true", "True", "1", 1 all mean true; same for false
- Timestamp parsing: handle various ISO formats, time zones, date-only strings
- Documents without metadata: exclude them (we can't verify they're public)
- Guest-owned documents: if
owner_idis null, comparing null to null shouldn't count as an owner edit
Complexity Analysis
Let N = number of edits, D = number of documents.
Time: O(N + D) for parsing and hash-based joins/groupings, plus O(K log K) to sort K output dates Space: O(N + D) for the joined data
Python Solution (pandas)
import pandas as pd
NULL_STRINGS = {"", "null", "none", "nan"}
TRUE_STRINGS = {"true", "t", "1", "yes"}
FALSE_STRINGS = {"false", "f", "0", "no"}
def normalize_id(series: pd.Series) -> pd.Series:
"""Convert IDs to strings, handling nulls and float representations."""
s = series.astype("string").str.strip()
# Remove trailing .0 from floats like "101.0"
s = s.str.replace(r"\.0$", "", regex=True)
# Treat common null representations as actual nulls
return s.mask(s.str.lower().isin(NULL_STRINGS))
def calculate_contributor_distribution(edits: pd.DataFrame,
documents: pd.DataFrame) -> pd.DataFrame:
result_columns = ["date", "percent_owner_edits", "percent_guest_edits"]
# Clean edit data
e = edits[["user_id", "doc_id", "timestamp"]].copy()
e["user_id"] = normalize_id(e["user_id"])
e["doc_id"] = normalize_id(e["doc_id"])
# Parse timestamps with timezone awareness
timestamps = pd.to_datetime(e["timestamp"], utc=True, errors="coerce")
e["date"] = timestamps.dt.date
# Remove unparseable rows and duplicates
e = e.dropna(subset=["doc_id", "date"]).drop_duplicates()
# Clean document metadata - keep only public documents
d = documents[["doc_id", "owner_id", "is_private"]].copy()
d["doc_id"] = normalize_id(d["doc_id"])
d["owner_id"] = normalize_id(d["owner_id"])
# Parse is_private flag
private_flag = d["is_private"].astype("string").str.strip().str.lower()
d = d[private_flag.isin(FALSE_STRINGS)].drop_duplicates(subset="doc_id")
# Join to attach owner information (inner join filters to public docs)
merged = e.merge(d[["doc_id", "owner_id"]], on="doc_id", how="inner")
if merged.empty:
return pd.DataFrame(columns=result_columns)
# Classify each edit
merged["is_guest"] = merged["user_id"].isna()
merged["is_owner"] = (merged["user_id"] == merged["owner_id"]).fillna(False)
# Stage 1: Aggregate to (date, doc_id) level
doc_daily = (merged.groupby(["date", "doc_id"], as_index=False)
.agg(has_owner_edit=("is_owner", "any"),
has_guest_edit=("is_guest", "any")))
# Stage 2: Aggregate to date level
daily_stats = (doc_daily.groupby("date", as_index=False)
.agg(total_docs=("doc_id", "size"),
docs_with_owner=("has_owner_edit", "sum"),
docs_with_guest=("has_guest_edit", "sum")))
# Calculate percentages
daily_stats["percent_owner_edits"] = (
100.0 * daily_stats["docs_with_owner"] / daily_stats["total_docs"]
).round(2)
daily_stats["percent_guest_edits"] = (
100.0 * daily_stats["docs_with_guest"] / daily_stats["total_docs"]
).round(2)
# Format and return
daily_stats["date"] = daily_stats["date"].astype(str)
return daily_stats[result_columns].sort_values("date").reset_index(drop=True)
SQL Solution
WITH doc_daily_activity AS (
SELECT
DATE(e.timestamp) AS date,
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 e
INNER JOIN documents d
ON e.doc_id = d.doc_id
AND d.is_private = FALSE
GROUP BY DATE(e.timestamp), e.doc_id
)
SELECT
date,
ROUND(100.0 * SUM(has_owner_edit) / COUNT(*), 2) AS percent_owner_edits,
ROUND(100.0 * SUM(has_guest_edit) / COUNT(*), 2) AS percent_guest_edits
FROM doc_daily_activity
GROUP BY date
ORDER BY date;
The SQL version uses MAX on 0/1 indicators to implement the "at least one" logic, which is equivalent to BOOL_OR in PostgreSQL or ANY_VALUE with booleans.
Common Mistakes
- Counting edits instead of documents: Computing percentages based on edit counts rather than document counts produces meaningless results
- Single-stage aggregation: Grouping directly from edits to dates without the intermediate document level
- Assuming percentages sum to 100: Forgetting that documents can have both types of edits
- Ignoring null representations: Not handling "NULL" as text or empty strings
- Type mismatches in joins: Comparing string IDs to numeric IDs fails silently
- Timezone issues: Not normalizing timestamps to UTC before extracting dates
What Evaluators Look For
- Explicit statement of the denominator and what each numerator represents
- Recognition that the two percentages can overlap
- Proper two-stage aggregation strategy
- Handling of messy real-world data (nulls, types, formats)
- Testing edge cases like empty results or documents with only non-owner collaborators