Shared-Document Analytics: Sources, Partners, and Country Rates
SQL & DataModel answerLast updated
Use deduplicated user-document pairs to analyze how collaborators arrive, who works most with a given user, and which country has the highest share of users who collaborate.
You have two CSV exports from a document-editing product and need to answer three questions about how people work together.
document_activity.csv (one row per view event)
| Column | Type | Meaning |
|---|---|---|
page_id | STRING | Document identifier |
user_id | STRING | Person who opened the document |
viewed_at | TIMESTAMP (UTC) | When the view happened |
is_creator | BOOLEAN | true if the viewer created the document |
collaborator_source | STRING, nullable | How a non-creator reached the document (e.g. invite link, email invite, search, direct). May be NULL, especially for creators |
users.csv
| Column | Type | Meaning |
|---|---|---|
user_id | STRING | Unique user identifier |
country | STRING | User's country |
Ground rules
- Join on
document_activity.user_id = users.user_id. - Use all rows; no date filtering.
- The same person may open a document many times. Unless a task asks for event counts, reduce the data to distinct
(page_id, user_id)pairs first. - A document has one creator and may have many collaborators.
Tasks
-
Source breakdown. Looking only at non-creators (
is_creator = false) and counting distinct(page_id, user_id)pairs, report how collaborators arrived. Output:collaborator_source,collaborator_count,collaborator_share. -
Closest partners of one user. Given a
user_id, find the other users who shared the most documents with them. Two users share a document if both viewed thatpage_idat least once. Count distinct shared documents, not views, and exclude the target. Output:target_user_id,co_user_id,shared_page_count. Return every user tied for the maximum. -
Country collaboration rate. A user "collaborated" if they appear on at least one document that has two or more distinct users in total. For each country compute
collaborating_users,total_users(distinct users of that country inusers.csv), andcollaboration_rate = collaborating_users / total_users. Rank countries from highest to lowest rate. Output:country,collaborating_users,total_users,collaboration_rate.
Write the solution in SQL or Python (pandas). Explain the assumptions you make about messy data, state the complexity, and mention edge cases you would test.
Hints
Hint 1
Build one deduplicated table of distinct (page_id, user_id) pairs first and derive all three answers from it, so view counts never leak into the metrics.
Hint 2
For task 1, a pair can show up with different sources on different views, and sources can be NULL. Decide on a rule (for example, the earliest view's source) and keep NULL as its own bucket so shares sum to 1.
Hint 3
For task 2, restrict to the target's pages before self-joining on page_id, then count distinct pages per co-user and keep all ties at the maximum. For task 3, take the denominator from users.csv and left join so countries with zero collaborators appear with rate 0.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Most errors in this problem come from using the wrong unit of analysis. Counting view events when the question asks about user-document relationships inflates every number. So the first step is to build a deduplicated table and use it everywhere:
pairs = DISTINCT (page_id, user_id) FROM document_activity
Task 1: Source distribution
- Keep only non-creator rows, then reduce to one row per
(page_id, user_id). - A pair may carry several
collaborator_sourcevalues across views. Counting distinct(page_id, user_id, source)would count one person-document relationship more than once. State a rule: attribute the pair to the source on its earliest view, since acquisition is a first-touch idea. - Keep
NULLas its own bucket. Dropping it silently means the shares no longer sum to 1. In pandas, usegroupby(..., dropna=False). collaborator_share = collaborator_count / total distinct non-creator pairs.- Dirty-data rule: if a user is flagged as creator on any row for a page, exclude that pair from this task.
Task 2: Top partners of a user
- Find the target's pages from
pairs. - Join
pairsto those pages onpage_idto list everyone else who appeared there. - Remove the target from the result.
- Group by co-user, count distinct pages, and keep rows equal to the maximum.
Because pairs is already distinct, each shared page yields exactly one row per co-user, so a row count equals the distinct page count. Using nunique is still the safer and clearer choice.
Filtering to the target's pages before the join matters. A full self-join costs O(Σ k_p²) where k_p is the number of users on page p, which explodes for a handful of very popular documents. The filtered version is O(P) in the number of pairs.
Return all ties, not just the first row.
Task 3: Country collaboration rate
- Count distinct users per page on
pairs; keep pages with at least 2. - Collect distinct users appearing on those pages. These are the collaborating users, and creators count.
- Start from
users.csv(the denominator), left join the collaborator flag, and group by country:collaborating_users = sum(flag),total_users = count(distinct user_id). - Rate is the ratio; sort descending with a deterministic tie-break (for example
total_usersdescending, thencountry).
Using users.csv as the base means users who never viewed anything still count in the denominator, and countries with no collaborators show up with a rate of 0. Activity rows whose user is missing from users.csv have no country and drop out.
SQL sketch
WITH pairs AS (
SELECT DISTINCT page_id, user_id FROM document_activity
),
shared AS (
SELECT page_id FROM pairs GROUP BY page_id HAVING COUNT(*) >= 2
),
collab AS (
SELECT DISTINCT p.user_id
FROM pairs p JOIN shared s USING (page_id)
)
SELECT u.country,
COUNT(c.user_id) AS collaborating_users,
COUNT(DISTINCT u.user_id) AS total_users,
COUNT(c.user_id) * 1.0 / COUNT(DISTINCT u.user_id) AS collaboration_rate
FROM users u
LEFT JOIN collab c ON c.user_id = u.user_id
GROUP BY u.country
ORDER BY collaboration_rate DESC, total_users DESC, u.country;
Python (pandas) sketch for Task 2
def top_collaborators(act, target):
pairs = act[["page_id", "user_id"]].drop_duplicates()
tp = pairs.loc[pairs.user_id == target, ["page_id"]]
co = pairs.merge(tp, on="page_id")
co = co[co.user_id != target]
if co.empty:
return pd.DataFrame(columns=["target_user_id", "co_user_id", "shared_page_count"])
c = (co.groupby("user_id")["page_id"].nunique()
.rename("shared_page_count").reset_index()
.rename(columns={"user_id": "co_user_id"}))
c = c[c.shared_page_count == c.shared_page_count.max()]
c.insert(0, "target_user_id", target)
return c.sort_values("co_user_id").reset_index(drop=True)
Complexity
Let E be events, P distinct pairs, U users.
| Task | Time | Space |
|---|---|---|
| 1 | O(E) to O(E log E) with sorting for first-touch | O(P) |
| 2 (filtered) | O(P) | O(P) |
| 2 (naive full self-join) | O(Σ k_p²) | O(Σ k_p²) |
| 3 | O(P + U) | O(P + U) |
Edge cases and common mistakes
- Counting events instead of distinct pairs, which inflates every metric.
- Dropping
NULLsources so shares do not sum to 1. - Using
head(1)and losing ties in task 2. - Computing
total_usersfrom the activity log instead ofusers.csv, which overstates rates and hides countries with zero collaborators. - Treating only non-creators as collaborators in task 3; creators with a second viewer also collaborated.
- Target user absent or only on solo pages: return an empty result rather than failing.
is_creatorread as strings from CSV: normalize to boolean.- Equal rates across countries: apply a deterministic tie-break.
- Small countries can post extreme rates (1 of 1 users is 100%); in practice, mention a minimum-size threshold or confidence interval before drawing conclusions.