Workspace Document Collaboration Metrics
Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen
Problem Statement
You are given two CSV logs from a cloud workspace product: a stream of page-view events and a directory of registered accounts. Implement CSV loaders and three analytical functions in Python to measure how collaborators discover shared pages, who works most closely with a given user, and how collaboration varies by country.
Input Schemas
-
document_activity.csv— each record represents a single page view:page_id(str): unique identifier of the page.user_id(str): identifier of the viewing account.viewed_at(datetime): UTC timestamp of the view event (ISO-8601 text in CSV, such as"2025-05-10T14:03:00Z"or"2025-05-10 14:03:00").is_creator(bool):Truewhen this viewer is the author who createdpage_id,Falseotherwise.collaborator_source(Optional[str]): acquisition channel through which a non-creator reached the page (for example,"slack_share","mention_email","workspace_search", or"bookmark"). Empty strings and"NULL"(any case) represent missing values (None).
-
users.csv— registered user directory:user_id(str): unique account identifier.country(str): ISO country code for the account.
Required Functions
read_activity(file: IO[str]) -> List[dict]: Parsedocument_activity.csvinto dictionaries with keys"page_id","user_id","viewed_at"(normalized to a timezone-aware UTCdatetime),"is_creator"(Truefor"true","t","1", or"yes"in any case;Falseotherwise), and"collaborator_source"(Nonewhen blank or"NULL", otherwise stripped text).read_users(file: IO[str]) -> List[dict]: Parseusers.csvinto dictionaries with stripped"user_id"and"country"strings.collaborator_source_distribution(activity: List[dict]) -> List[dict]:- Evaluate distinct non-creator
(page_id, user_id)pairs across the entire log. - Any
(page_id, user_id)pair that ever appears withis_creator=Trueis the page's author and must never be counted as a collaborator on thatpage_id, even if another row for the same pair logsis_creator=False. - Attribute each remaining
(page_id, user_id)pair to the channel from its earliest UTCviewed_atevent (substituting"unknown"whencollaborator_sourceisNone; if two earliest events have the exact same timestamp, break the tie alphabetically by channel name). - Return a list of
{"collaborator_source": str, "collaborator_count": int, "collaborator_share": float}dictionaries wherecollaborator_shareiscollaborator_count / total_collaborator_pairs, ordered bycollaborator_countdescending and thencollaborator_sourceascending (or[]when no collaborator pairs exist).
- Evaluate distinct non-creator
top_collaborators(activity: List[dict], target_user_id: str) -> List[dict]:- Two distinct users co-collaborate on a page whenever both have viewed that
page_idat least once (including page creators). - Count distinct shared
page_ids betweentarget_user_idand every other user (co_user_id != target_user_id). - Return
{"target_user_id": str, "co_user_id": str, "shared_page_count": int}for every co-user tied at the highestshared_page_count(>= 1), sorted ascending byco_user_id. Return[]iftarget_user_idhas no shared pages.
- Two distinct users co-collaborate on a page whenever both have viewed that
country_collaboration_rates(activity: List[dict], users: List[dict]) -> List[dict]:- A user counts as collaborating if at least one
page_idthey viewed has2or more distinctuser_ids acrossactivity(even if another viewer on that page is absent fromusers). - For each country in
users, computetotal_users(distinctuser_ids inusersfor that country, including accounts with zero page views),collaborating_users(how many of those country users collaborated), andcollaboration_rate = collaborating_users / total_users. - Return
{"country": str, "collaborating_users": int, "total_users": int, "collaboration_rate": float}ordered bycollaboration_ratedescending and thencountryascending.
- A user counts as collaborating if at least one
Examples
Example 1
Input:
activity:
page_id user_id viewed_at is_creator collaborator_source
-------- ------- -------------------- ---------- -------------------
doc-10 ava 2025-05-10T14:01:00Z True None
doc-10 ben 2025-05-10T14:03:00Z False "slack_share"
doc-10 ben 2025-05-10T14:09:00Z False "bookmark"
doc-10 cora 2025-05-10T14:04:00Z False "mention_email"
doc-20 ben 2025-05-10T14:05:00Z True None
doc-20 ava 2025-05-10T14:06:00Z False "slack_share"
doc-20 ava 2025-05-10T14:07:00Z False "slack_share"
doc-20 cora 2025-05-10T14:08:00Z False "workspace_search"
doc-30 dev 2025-05-10T14:10:00Z True None
doc-30 ava 2025-05-10T14:12:00Z False "bookmark"
doc-40 eli 2025-05-10T14:15:00Z True None
users:
ava -> JP, ben -> JP, finn -> JP
cora -> GB, dev -> GB, eli -> GB, gina -> GB
Output:
collaborator_source_distribution(activity)
# [
# {"collaborator_source": "slack_share", "collaborator_count": 2, "collaborator_share": 0.4},
# {"collaborator_source": "bookmark", "collaborator_count": 1, "collaborator_share": 0.2},
# {"collaborator_source": "mention_email", "collaborator_count": 1, "collaborator_share": 0.2},
# {"collaborator_source": "workspace_search", "collaborator_count": 1, "collaborator_share": 0.2},
# ]
top_collaborators(activity, "ava")
# [
# {"target_user_id": "ava", "co_user_id": "ben", "shared_page_count": 2},
# {"target_user_id": "ava", "co_user_id": "cora", "shared_page_count": 2},
# ]
country_collaboration_rates(activity, users)
# [
# {"country": "JP", "collaborating_users": 2, "total_users": 3, "collaboration_rate": 0.6666666666666666},
# {"country": "GB", "collaborating_users": 2, "total_users": 4, "collaboration_rate": 0.5},
# ]
Explanation:
- For collaborator_source_distribution, the five distinct non-creator pairs are ("doc-10", "ben") -> "slack_share" (its 14:03 arrival beats the 14:09 revisit), ("doc-10", "cora") -> "mention_email", ("doc-20", "ava") -> "slack_share" (deduplicated across two views), ("doc-20", "cora") -> "workspace_search", and ("doc-30", "ava") -> "bookmark".
- For top_collaborators(activity, "ava"), "ava" co-views "doc-10" and "doc-20" with both "ben" and "cora" (2 pages each) and "doc-30" with "dev" (1 page), so "ben" and "cora" tie for first.
- For country_collaboration_rates, pages "doc-10", "doc-20", and "doc-30" each have multiple viewers ({"ava", "ben", "cora", "dev"}), while "doc-40" has only "eli" and "finn" / "gina" have zero views. Thus "JP" has 2 / 3 collaborating accounts and "GB" has 2 / 4 = 0.5.
Example 2
Input:
document_activity.csv:
page_id,user_id,viewed_at,is_creator,collaborator_source
spec-1,u10,2025-06-01T08:00:00Z,true,
spec-1,u10,2025-06-01T08:05:00Z,false,direct_url
spec-1,u20,2025-06-01 08:10:00,FALSE,NULL
users.csv:
user_id,country
u10,SE
u30,SE
Output:
collaborator_source_distribution(activity)
# [{"collaborator_source": "unknown", "collaborator_count": 1, "collaborator_share": 1.0}]
top_collaborators(activity, "u10")
# [{"target_user_id": "u10", "co_user_id": "u20", "shared_page_count": 1}]
country_collaboration_rates(activity, users)
# [{"country": "SE", "collaborating_users": 1, "total_users": 2, "collaboration_rate": 0.5}]
Explanation: "u10" created "spec-1", so "u10"'s later 08:05 reload with is_creator=false is still excluded from collaborator channels. "u20" has a NULL channel mapped to "unknown" and makes "spec-1" a two-person page even though "u20" does not appear in users.csv, giving "SE" 1 collaborating user ("u10") out of 2 registered users ("u10" and "u30").
Constraints
- Use every event in
activity; do not apply any date window filter. viewed_atvalues insideactivitydictionaries passed directly to the metric functions may be either timezone-aware/naive UTCdatetimeobjects or ISO-8601 UTC timestamp strings.- Floating-point outputs (
collaborator_shareandcollaboration_rate) are compared within1e-9tolerance. - Empty inputs must be handled without division-by-zero errors (
collaborator_source_distribution([]) == [],top_collaborators([], target) == [], andcountry_collaboration_rates([], users)reports0.0for each country inusers).
Step-by-step walkthrough
Restate the three tasks and pin down edge-case rules
We are given two tables: -
document_activity: raw view events(page_id, user_id, viewed_at, is_creator, collaborator_source). -users: user directory(user_id, country).Every collaboration metric here asks about unique
(page_id, user_id)pairs, never raw view counts. Before writing a line of code, state how we resolve the real-world edge cases hidden in event logs:- Multiple views with different sources (Task 1): User
benmight first open pagedoc-10via"slack_share"at14:03and reopen it via"bookmark"at14:09. Counting(doc-10, ben)under both sources would make shares exceed100%. We use first-touch attribution: each collaborator pair gets the source of its earliest view timestamp (breaking exact timestamp ties alphabetically by source name). - Missing
collaborator_sourceon a non-creator (Task 1): We mapNULL/ empty strings to"unknown"instead of dropping the pair, so every true collaborator stays in the denominator and shares sum to1.0. - Creators are never collaborators on their own page (Task 1): Even if a messy log row records
is_creator = falsefor the page's creator on a later reload, that(page_id, user_id)pair is still the creator and is excluded from Task 1. - Who counts as collaborating on a page (Tasks 2 & 3): Both creators and non-creators count as viewers of a page. If page
doc-10has{ava (creator), ben (viewer)}, bothavaandbencollaborated ondoc-10. - Country denominator and unmapped users (Task 3):
total_userscomes fromusers.csv(so signed-up users with zero views still count in the denominator with0collaborations). Conversely, if a guest viewer missing fromusers.csvviews pagespec-1alongsideu10, pagespec-1still has2distinct users sou10collaborated, while the unmapped guest belongs to no country bucket.
- Multiple views with different sources (Task 1): User
Parse CSV files cleanly at the boundary
CSV files deliver every column as a raw string, so
read_activityandread_usersconvert types once at ingestion:- Booleans: Never write
bool(raw["is_creator"])— in Python,bool("false")evaluates toTruebecause any non-empty string is truthy! Checkraw["is_creator"].strip().lower() in ("true", "t", "1", "yes"). - Null sources: Convert
""and"NULL"(case-insensitive) toNone. - UTC timestamps: Normalize trailing
"Z"to"+00:00", parse withdatetime.fromisoformat, and attach or convert totimezone.utcso"2024-03-01 09:30:00"and"2024-03-01T08:00:00Z"compare by true instant in time rather than ASCII character order (' ' < 'T').
from typing import Dict, IO, List, Optional import csv from datetime import datetime, timezone UNKNOWN_SOURCE = "unknown" TRUE_VALUES = ("true", "t", "1", "yes") def _parse_timestamp(text: str) -> datetime: cleaned = text.strip() # Normalize trailing 'Z' to '+00:00' so UTC ISO strings parse cleanly in every Python 3 version if cleaned.endswith(("Z", "z")): cleaned = cleaned[:-1] + "+00:00" moment = datetime.fromisoformat(cleaned) if moment.tzinfo is None: return moment.replace(tzinfo=timezone.utc) return moment.astimezone(timezone.utc) def _to_utc_datetime(value) -> datetime: # Accept either an already-parsed datetime or a raw ISO timestamp string if isinstance(value, datetime): if value.tzinfo is None: return value.replace(tzinfo=timezone.utc) return value.astimezone(timezone.utc) return _parse_timestamp(str(value)) def read_activity(file: IO[str]) -> List[dict]: rows = [] for raw in csv.DictReader(file): source = (raw.get("collaborator_source") or "").strip() if source == "" or source.upper() == "NULL": source = None is_creator = raw["is_creator"].strip().lower() in TRUE_VALUES rows.append({ "page_id": raw["page_id"].strip(), "user_id": raw["user_id"].strip(), "viewed_at": _parse_timestamp(raw["viewed_at"]), "is_creator": is_creator, "collaborator_source": source, }) return rows def read_users(file: IO[str]) -> List[dict]: rows = [] for raw in csv.DictReader(file): rows.append({ "user_id": raw["user_id"].strip(), "country": raw["country"].strip(), }) return rows- Booleans: Never write
Core building block: collapse events into distinct `(page, user)` sets
If a user refreshes one shared document 20 times, counting raw events would pretend they collaborated on 20 documents. Grouping
activityinto a dictionarypage_id -> set of distinct user_idsdeduplicates repeated views in a singleO(E)pass:Raw events: Deduplicated _users_by_page: (doc-10, ava), (doc-10, ben), --> "doc-10": {"ava", "ben", "cora"} (3 distinct users -> shared!) (doc-10, ben), (doc-10, cora), "doc-40": {"eli"} (1 user -> solo page) (doc-40, eli)Both Task 2 and Task 3 can be answered directly from this one helper:
def _users_by_page(activity: List[dict]) -> Dict[str, set]: # users_by_page: maps page_id -> set of distinct user_ids, e.g. {"A": {"u1", "u2"}} users_by_page: Dict[str, set] = {} for row in activity: page_id = row["page_id"] if page_id not in users_by_page: users_by_page[page_id] = set() users_by_page[page_id].add(row["user_id"]) return users_by_pageTask 1: attribution of collaborator sources
Task 1 needs each non-creator
(page_id, user_id)pair's earliest acquisition source. We compute it in three clean steps:- Collect
creator_pairs: Scan all rows first to find every(page_id, user_id)withis_creator == True. Doing this in a separate first pass ensures we recognize a creator even if theiris_creator = Truerow appears after anis_creator = Falserow in an unsorted file. - Find each pair's earliest view: For every row not in
creator_pairs, buildcandidate = (_to_utc_datetime(row["viewed_at"]), source)and keep the minimum tuple per(page_id, user_id). - Aggregate and compute shares: Count how many distinct pairs landed in each
source, divide bytotal_pairs = len(first_view), and sort by(-collaborator_count, collaborator_source). Iffirst_viewis empty,countsis empty and the loop returns[]without dividing by zero.
def _source_order(row: dict): # Highest collaborator_count first; break count ties alphabetically by source name return (-row["collaborator_count"], row["collaborator_source"]) def collaborator_source_distribution(activity: List[dict]) -> List[dict]: creator_pairs = set() for row in activity: if row["is_creator"]: creator_pairs.add((row["page_id"], row["user_id"])) first_view: Dict[tuple, tuple] = {} for row in activity: pair = (row["page_id"], row["user_id"]) if row["is_creator"] or pair in creator_pairs: continue source = row["collaborator_source"] or UNKNOWN_SOURCE viewed_at = _to_utc_datetime(row["viewed_at"]) candidate = (viewed_at, source) if pair not in first_view or candidate < first_view[pair]: first_view[pair] = candidate counts: Dict[str, int] = {} for _, source in first_view.values(): counts[source] = counts.get(source, 0) + 1 total_pairs = len(first_view) result = [] for source, count in counts.items(): result.append({ "collaborator_source": source, "collaborator_count": count, "collaborator_share": count / total_pairs, }) result.sort(key=_source_order) return result- Collect
Task 2: co-users sharing the most distinct pages
Given
target_user_id, walk through_users_by_page(activity):- Skip any page whose user set does not contain
target_user_id. - For every page that does contain
target_user_id, add1toshared_counts[user_id]for each other user on that page (user_id != target_user_id). Becauseusers_on_pageis already aset, each shared page adds1regardless of view count. - If
shared_countsis empty (the target never viewed a page, or only viewed solo pages), return[]. Otherwise findmax_shared = max(shared_counts.values())and return all tied co-users in sortedco_user_idorder.
def top_collaborators(activity: List[dict], target_user_id: str) -> List[dict]: shared_counts: Dict[str, int] = {} for users_on_page in _users_by_page(activity).values(): if target_user_id not in users_on_page: continue for user_id in users_on_page: if user_id != target_user_id: shared_counts[user_id] = shared_counts.get(user_id, 0) + 1 if not shared_counts: return [] max_shared = max(shared_counts.values()) result = [] for co_user_id in sorted(shared_counts): if shared_counts[co_user_id] == max_shared: result.append({ "target_user_id": target_user_id, "co_user_id": co_user_id, "shared_page_count": max_shared, }) return result- Skip any page whose user set does not contain
Task 3: country-level collaboration rates
A user has "collaborated with others" if at least one page they viewed has
2or more distinct users in total:- Find all collaborating users: Loop over
_users_by_page(activity). Wheneverlen(users_on_page) >= 2, add everyone inusers_on_pagetocollaborating_user_ids. - Group
users.csvby country: Buildusers_by_country[country] = set_of_distinct_user_idsfromusers. Using asetprotects against duplicate rows inusers.csv, and starting fromuserspreserves inactive users intotal_users. - Compute rates and rank: For each country, count how many of its
country_user_idsbelong tocollaborating_user_ids, divide bylen(country_user_ids), and sort by(-collaboration_rate, country).
def _rate_order(row: dict): # Highest collaboration_rate first; break rate ties alphabetically by country return (-row["collaboration_rate"], row["country"]) def country_collaboration_rates(activity: List[dict], users: List[dict]) -> List[dict]: collaborating_user_ids = set() for users_on_page in _users_by_page(activity).values(): if len(users_on_page) >= 2: collaborating_user_ids.update(users_on_page) users_by_country: Dict[str, set] = {} for row in users: country = row["country"] if country not in users_by_country: users_by_country[country] = set() users_by_country[country].add(row["user_id"]) result = [] for country, country_user_ids in users_by_country.items(): collaborating_count = 0 for user_id in country_user_ids: if user_id in collaborating_user_ids: collaborating_count += 1 total_users = len(country_user_ids) result.append({ "country": country, "collaborating_users": collaborating_count, "total_users": total_users, "collaboration_rate": collaborating_count / total_users, }) result.sort(key=_rate_order) return result- Find all collaborating users: Loop over
Trace all three tasks on Example 1
document_activity: users: page_id user min is_creator source ava: JP cora: GB ------- ---- --- ---------- ---------------- ben: JP dev: GB doc-10 ava 1 True None finn: JP eli: GB doc-10 ben 3 False slack_share gina: GB doc-10 ben 9 False bookmark doc-10 cora 4 False mention_email doc-20 ben 5 True None doc-20 ava 6 False slack_share doc-20 ava 7 False slack_share doc-20 cora 8 False workspace_search doc-30 dev 10 True None doc-30 ava 12 False bookmark doc-40 eli 15 True None_users_by_page:doc-10: {ava, ben, cora},doc-20: {ava, ben, cora},doc-30: {ava, dev},doc-40: {eli}.- Task 1 (sources): Distinct non-creator pairs are
(doc-10, ben) -> slack_share(min 3 beats min 9),(doc-10, cora) -> mention_email,(doc-20, ava) -> slack_share(deduplicated),(doc-20, cora) -> workspace_search, and(doc-30, ava) -> bookmark. Out of5pairs:slack_sharehas2(0.4), andbookmark,mention_email,workspace_searcheach have1(0.2). - Task 2 (
target_user_id = "ava"):avaappears ondoc-10(withben, cora),doc-20(withben, cora), anddoc-30(withdev). Shared page counts:ben: 2,cora: 2,dev: 1. Both ties(ava, ben, 2)and(ava, cora, 2)are returned! - Task 3 (countries): Multi-user pages are
doc-10, doc-20, doc-30, givingcollaborating_user_ids = {ava, ben, cora, dev}.JPhas{ava, ben, finn}(finnnever viewed anything):2 / 3 ≈ 0.667.GBhas{cora, dev, eli, gina}(elionly viewed solo pagedoc-40,ginainactive):2 / 4 = 0.5.JPranks ahead ofGB.
Complete solution
from typing import Dict, IO, List, Optional import csv from datetime import datetime, timezone UNKNOWN_SOURCE = "unknown" TRUE_VALUES = ("true", "t", "1", "yes") def _parse_timestamp(text: str) -> datetime: cleaned = text.strip() # Normalize trailing 'Z' to '+00:00' so UTC ISO strings parse cleanly in every Python 3 version if cleaned.endswith(("Z", "z")): cleaned = cleaned[:-1] + "+00:00" moment = datetime.fromisoformat(cleaned) if moment.tzinfo is None: return moment.replace(tzinfo=timezone.utc) return moment.astimezone(timezone.utc) def _to_utc_datetime(value) -> datetime: # Accept either an already-parsed datetime or a raw ISO timestamp string if isinstance(value, datetime): if value.tzinfo is None: return value.replace(tzinfo=timezone.utc) return value.astimezone(timezone.utc) return _parse_timestamp(str(value)) def read_activity(file: IO[str]) -> List[dict]: rows = [] for raw in csv.DictReader(file): # Convert empty strings and literal 'NULL' markers into Python None source = (raw.get("collaborator_source") or "").strip() if source == "" or source.upper() == "NULL": source = None # Compare lowercase string explicitly because bool("false") is True in Python is_creator = raw["is_creator"].strip().lower() in TRUE_VALUES rows.append({ "page_id": raw["page_id"].strip(), "user_id": raw["user_id"].strip(), "viewed_at": _parse_timestamp(raw["viewed_at"]), "is_creator": is_creator, "collaborator_source": source, }) return rows def read_users(file: IO[str]) -> List[dict]: rows = [] for raw in csv.DictReader(file): rows.append({ "user_id": raw["user_id"].strip(), "country": raw["country"].strip(), }) return rows def _users_by_page(activity: List[dict]) -> Dict[str, set]: # users_by_page: maps page_id -> set of distinct user_ids, e.g. {"A": {"u1", "u2"}} users_by_page: Dict[str, set] = {} for row in activity: page_id = row["page_id"] if page_id not in users_by_page: users_by_page[page_id] = set() users_by_page[page_id].add(row["user_id"]) return users_by_page def _source_order(row: dict): # Highest collaborator_count first; break count ties alphabetically by source name return (-row["collaborator_count"], row["collaborator_source"]) def collaborator_source_distribution(activity: List[dict]) -> List[dict]: # Phase 1: record (page_id, user_id) pairs that created the page so creators are never counted # even if a noisy later event logs is_creator=False for the same creator on that page creator_pairs = set() for row in activity: if row["is_creator"]: creator_pairs.add((row["page_id"], row["user_id"])) # Phase 2: first-touch attribution per non-creator (page_id, user_id) pair # first_view: {(page_id, user_id): (utc_viewed_at, source_name)} first_view: Dict[tuple, tuple] = {} for row in activity: pair = (row["page_id"], row["user_id"]) if row["is_creator"] or pair in creator_pairs: continue source = row["collaborator_source"] or UNKNOWN_SOURCE viewed_at = _to_utc_datetime(row["viewed_at"]) # Tuple comparison picks the earliest timestamp, breaking exact timestamp ties by source candidate = (viewed_at, source) if pair not in first_view or candidate < first_view[pair]: first_view[pair] = candidate # Phase 3: aggregate distinct pairs per source and compute each source's share of total pairs counts: Dict[str, int] = {} for _, source in first_view.values(): counts[source] = counts.get(source, 0) + 1 total_pairs = len(first_view) result = [] for source, count in counts.items(): result.append({ "collaborator_source": source, "collaborator_count": count, "collaborator_share": count / total_pairs, }) result.sort(key=_source_order) return result def top_collaborators(activity: List[dict], target_user_id: str) -> List[dict]: # shared_counts: maps co_user_id -> count of distinct pages shared with target_user_id shared_counts: Dict[str, int] = {} for users_on_page in _users_by_page(activity).values(): if target_user_id not in users_on_page: continue for user_id in users_on_page: if user_id != target_user_id: shared_counts[user_id] = shared_counts.get(user_id, 0) + 1 if not shared_counts: return [] # Return every co-user tied at the maximum shared page count, sorted by co_user_id max_shared = max(shared_counts.values()) result = [] for co_user_id in sorted(shared_counts): if shared_counts[co_user_id] == max_shared: result.append({ "target_user_id": target_user_id, "co_user_id": co_user_id, "shared_page_count": max_shared, }) return result def _rate_order(row: dict): # Highest collaboration_rate first; break rate ties alphabetically by country return (-row["collaboration_rate"], row["country"]) def country_collaboration_rates(activity: List[dict], users: List[dict]) -> List[dict]: # Phase 1: any user on a page with >= 2 distinct viewers (even unmapped viewers) collaborated collaborating_user_ids = set() for users_on_page in _users_by_page(activity).values(): if len(users_on_page) >= 2: collaborating_user_ids.update(users_on_page) # Phase 2: build the denominator per country from users.csv (including users with 0 activity) users_by_country: Dict[str, set] = {} for row in users: country = row["country"] if country not in users_by_country: users_by_country[country] = set() users_by_country[country].add(row["user_id"]) # Phase 3: compute collaborating_users / total_users for each country result = [] for country, country_user_ids in users_by_country.items(): collaborating_count = 0 for user_id in country_user_ids: if user_id in collaborating_user_ids: collaborating_count += 1 total_users = len(country_user_ids) result.append({ "country": country, "collaborating_users": collaborating_count, "total_users": total_users, "collaboration_rate": collaborating_count / total_users, }) result.sort(key=_rate_order) return result✅ Submit now — all tests should pass.
Intuition & how it works
Imagine analyzing collaboration in a workspace by reading a door-badge swipe log: if Alice walks into Conference Room A ten times while Bob walks in once, two people collaborated in Room A — not eleven! Analytics questions over event logs almost always require changing the grain (the unit a single row represents) from raw view events down to deduplicated (page_id, user_id) pairs (keeping each unique user-on-page combination once) before counting sources, co-workers, or country rates.
Computing metrics directly on raw view rows fails in every single task. Refreshing a page ten times would count one collaborator ten times in Task 1 (and assigning multiple sources to the same user-page pair would push source percentages past 100%), let a chatty single-page co-worker outrank someone who collaborated across five separate projects in Task 2, and — if you inner-join document_activity to users.csv — silently erase inactive sign-ups from each country's total_users denominator in Task 3. Instead, we collapse views into per-page user sets (page_id -> {distinct user_ids}) and use first-touch attribution (assigning a user-document pair the source from its very first view in time) for Task 1.
Walk through a tiny 4-event trace with users = [(ava, JP), (ben, JP), (eli, JP)]:
1. Events: (doc-10, ava, t=1, creator=True), (doc-10, ben, t=3, creator=False, source="slack_share"), (doc-10, ben, t=9, creator=False, source="bookmark"), (doc-40, eli, t=15, creator=True).
2. Task 1: Only (doc-10, ben) is a non-creator pair; its earliest view (t=3) gives "slack_share": 1 (100% share).
3. Task 2 (target = ava): doc-10 has {ava, ben}, so ben is ava's top collaborator with shared_page_count = 1.
4. Task 3: doc-10 has 2 users ({ava, ben} collaborated), while doc-40 has 1 user ({eli} worked solo), so JP has 2 collaborating users out of 3 total users (collaboration_rate = 2/3).
Complexity
Let E be the number of rows in document_activity, P be the number of distinct (page_id, user_id) pairs (P <= E), S be the number of distinct source names, U be the number of rows in users, and C be the number of distinct countries (C <= U).
- CSV parsing (
read_activity,read_users) —O(E + U)time and space: Each CSV row is read, stripped, and converted once into a dictionary. - Task 1 (
collaborator_source_distribution) —O(E + P + S log S)time,O(P)space: Two linear passes over theEevents buildcreator_pairsandfirst_viewusingO(1)expected dictionary lookups per row, one pass overPpairs tallies counts per source, and sorting the handful ofSsource buckets (S <= P) finishes the output. - Task 2 (
top_collaborators) —O(E + K log K)time,O(P)space whereKis the number of distinct co-users of the target: OneO(E)pass builds_users_by_page(O(P)stored user-page entries across all sets), scanning pages containingtarget_user_idtouches at mostPentries, and sorting theKco-user IDs takesO(K log K). - Task 3 (
country_collaboration_rates) —O(E + U + C log C)time,O(P + U)space: OneO(E)pass builds_users_by_pageand collectscollaborating_user_ids, oneO(U)pass groupsusersinto per-country user sets, and sorting theCcountry summaries takesO(C log C).
Edge cases
- Repeated views of the same page: Collapsed by
setmembership in Tasks 2 & 3 and byfirst_viewdictionary keys in Task 1, so refreshing a page 50 times never inflates any count. - Collaborator returns later via a different channel:
(page_id, user_id)takes the source of its earliest UTC timestamp; exact timestamp ties break alphabetically by source name for deterministic output. - Mixed timestamp string formats (
"2024-03-01 09:30:00"vs"2024-03-01T08:00:00Z"): Normalized to UTCdatetimeobjects before comparison so"08:00Z"beats"09:30"even though ASCII' 'sorts before'T'. - Missing or
"NULL"collaborator_sourceon a non-creator: Bucketed as"unknown"rather than dropped, keeping all shares honest and summing to1.0. - Creator logged again with
is_creator = False: Caught by the first-passcreator_pairsset so a document's creator is never miscounted as a collaborator on their own document. - Empty activity or zero collaborators: Task 1 and Task 2 return
[]cleanly without dividing by zero; Task 3 reports0collaborating users and0.0rate for every country inusers.csv. - Co-viewer missing from
users.csv: Determining whether a page has>= 2users before joining tousersensures that collaborating with an unmapped guest user still counts as collaboration for known users. - Ties in Task 2 and Task 3: Task 2 returns all co-users tied at
max_sharedsorted byco_user_id; Task 3 breaks equal collaboration rates alphabetically bycountry.
Common mistakes
- Writing
bool(row["is_creator"])on CSV text: In Python, any non-empty string — including"false"and"0"— is truthy (bool("false") == True), which mistakenly flags every viewer as a creator! - Counting raw view events instead of distinct
(page_id, user_id)pairs: Inflates frequent readers in source shares and co-collaborator rankings. - Dropping
NULLcollaborator sources in Task 1: FilteringWHERE collaborator_source IS NOT NULLshrinks the denominator and overstates every remaining channel's share. - Using an
INNER JOINonactivityto computetotal_usersin Task 3: Drops registered users who never viewed a document, turning "collaboration rate across all users in a country" into "collaboration rate among active viewers only." - Joining
users.csvbefore checkinglen(users_on_page) >= 2: Drops guest viewers missing fromusers.csv, making a 2-person shared document look like a 1-person solo document. - Using
LIMIT 1in Task 2: Silently discards tied top collaborators when multiple co-users share the same maximum document count.
Alternative approaches
In an analytics interview, you can also express all three tasks cleanly in standard SQL using CTEs (Common Table Expressions, named WITH subqueries that break complex SQL into readable steps) and window functions (SQL functions like ROW_NUMBER() OVER (...) or SUM(...) OVER () that compute rankings or totals across related rows without collapsing them):
-- Task 1: First-touch source distribution over non-creator (page_id, user_id) pairs
WITH non_creator_views AS (
SELECT a.page_id,
a.user_id,
a.viewed_at,
COALESCE(a.collaborator_source, 'unknown') AS source
FROM document_activity a
WHERE a.is_creator = FALSE
-- Exclude anyone who ever appeared as creator on the same page
AND NOT EXISTS (
SELECT 1
FROM document_activity c
WHERE c.is_creator = TRUE
AND c.page_id = a.page_id
AND c.user_id = a.user_id
)
),
ranked_views AS (
SELECT source,
ROW_NUMBER() OVER (
PARTITION BY page_id, user_id
ORDER BY viewed_at ASC, source ASC
) AS rn
FROM non_creator_views
)
SELECT source AS collaborator_source,
COUNT(*) AS collaborator_count,
1.0 * COUNT(*) / SUM(COUNT(*)) OVER () AS collaborator_share
FROM ranked_views
WHERE rn = 1
GROUP BY source
ORDER BY collaborator_count DESC, collaborator_source ASC;
-- Task 2: Co-users with the maximum shared distinct page count for :target_user_id
WITH distinct_pairs AS (
SELECT DISTINCT page_id, user_id
FROM document_activity
),
shared_pages AS (
SELECT t.user_id AS target_user_id,
o.user_id AS co_user_id,
COUNT(*) AS shared_page_count
FROM distinct_pairs t
JOIN distinct_pairs o
ON o.page_id = t.page_id
AND o.user_id <> t.user_id
WHERE t.user_id = :target_user_id
GROUP BY t.user_id, o.user_id
)
SELECT target_user_id, co_user_id, shared_page_count
FROM shared_pages
WHERE shared_page_count = (SELECT MAX(shared_page_count) FROM shared_pages)
ORDER BY co_user_id ASC;
-- Task 3: Country collaboration rate keeping inactive users in the denominator via LEFT JOIN
WITH distinct_pairs AS (
SELECT DISTINCT page_id, user_id
FROM document_activity
),
shared_page_ids AS (
SELECT page_id
FROM distinct_pairs
GROUP BY page_id
HAVING COUNT(*) >= 2
),
collaborating_users AS (
SELECT DISTINCT p.user_id
FROM distinct_pairs p
JOIN shared_page_ids s ON s.page_id = p.page_id
)
SELECT u.country,
COUNT(DISTINCT c.user_id) AS collaborating_users,
COUNT(DISTINCT u.user_id) AS total_users,
1.0 * COUNT(DISTINCT c.user_id) / COUNT(DISTINCT u.user_id) AS collaboration_rate
FROM users u
LEFT JOIN collaborating_users c ON c.user_id = u.user_id
GROUP BY u.country
ORDER BY collaboration_rate DESC, u.country ASC;
Follow-up questions
-
How can you prevent countries with only one or two registered accounts from dominating the collaboration rate leaderboard? Raw proportions are noisy at tiny sample sizes:
1 / 1 = 1.00beats900 / 1,000 = 0.90even though900 / 1,000is far stronger evidence of high collaboration. In production dashboards, either enforce a minimum cohort threshold (e.g.,HAVING COUNT(DISTINCT u.user_id) >= 50), apply empirical Bayes shrinkage (blending each country's raw rate toward the global average in proportion to its sample size), or rank by the 95% Wilson score lower confidence bound (the conservative bottom edge of the 95% binomial confidence interval, which scores1/1at0.207while scoring90/100at0.826) while still displaying rawcollaboration_rateandtotal_usersalongside it. -
If you needed the top collaborator for every user across millions of pages—including company-wide announcements viewed by thousands of employees—how would you avoid a quadratic self-join blowup? A naive self-join (joining
distinct_pairsto itself onpage_id) emitsm * (m - 1)pairs for a page ofmviewers, so one10,000-viewer all-hands page explodes into~10^8pairs while adding almost zero real 1-on-1 collaboration signal! First, cap or down-weight mega-pages (for instance, ignore pages withm > 200viewers, or weight each shared page by1 / (m - 1)so a 2-person page contributes1.0while a 101-person page contributes0.01). Second, if exact pairwise counts are still too large, estimate Jaccard similarity (shared pages divided by total combined pages of two users) using MinHash (compact fixed-size random hash signatures of each user's page set) paired with locality-sensitive hashing (bucketing similar signatures together so only likely high-overlap user pairs are compared). -
How would the acquisition breakdown change if you switched from first-touch attribution to last-touch or event-level attribution? Very substantially, which is why analysts always state the attribution rule explicitly alongside the numbers. On Example 1, first-touch over distinct pairs gives
slack_share = 40%(2/5) andbookmark = 20%(1/5), whereas last-touch attribution (crediting the most recent view of(doc-10, ben)at minute 9) flips(doc-10, ben)fromslack_sharetobookmark, tyingbookmarkat40%! First-touch measures acquisition (what brought a new collaborator onto the page for the first time), whereas event-level shares measure ongoing engagement (how collaborators return day after day).
Follow-up questions
- How can you prevent countries with only one or two registered accounts from dominating the collaboration rate leaderboard?
- If you needed the top collaborator for every user across millions of pages—including company-wide announcements viewed by thousands of employees—how would you avoid a quadratic self-join blowup?
- How would the acquisition breakdown change if you switched from first-touch attribution to last-touch or event-level attribution?
Similar questions
- Owner and Guest Document Edit Rates
- 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
- Owner and Guest Document Edit Rates Medium
- Workspace Document Collaboration Metrics Easy
- 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