Workspace Document Collaboration Metrics
Easy · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen
Problem Statement
Given parsed workspace activity records access_rows, a user directory user_rows, and a query identifier target_user_id, compute three document-level collaboration summaries and return them in a single dictionary {"q1": ..., "q2": ..., "q3": ...}.
def analyze_document_collaboration(
access_rows: List[Dict], user_rows: List[Dict], target_user_id
) -> Dict:
...
Input Records
access_rows: each dictionary records one page-open event and contains:page_id(strorint): document identifier.user_id(strorint): user who opened the page.event_ts(str): UTC timestamp string comparable in chronological order.is_creator(bool):Truefor the page author;Falsefor a non-author collaborator.collab_source(Optional[str]): acquisition channel for collaborator visits (is_creator == False);Nonefor author visits. TreatNoneor""on a collaborator row as"unknown".
user_rows: each dictionary maps a registered account to its country viauser_id(strorint) andcountry(str). Ifuser_rowsrepeats auser_id, keep the latest entry for that user.
Because an account can open the same document repeatedly, collapse repeated visits to distinct (page_id, user_id) page memberships before counting.
Required Summaries
"q1"— Collaborator channel breakdown (List[Dict]):- Filter to non-author rows (
is_creator == False) and deduplicate by(page_id, user_id). When one(page_id, user_id)pair appears with multiple timestamps or channels, keep the channel from its earliestevent_ts(preserving first appearance inaccess_rowsif timestamps are identical). - Return one dictionary per distinct channel, sorted ascending by
collab_source, containing:"collab_source"(str)"num_collaborators"(int): count of deduplicated(page_id, user_id)collaborator memberships attributed to that channel"pct_of_collaborators"(float):100.0 * num_collaborators / total_collaborator_memberships(on a0to100scale)
- Return
[]if zero collaborator memberships exist.
- Filter to non-author rows (
"q2"— Top co-collaborator fortarget_user_id(Dict):- Treat every distinct
(page_id, user_id)pair (authors and non-authors alike) as a member ofpage_id. Two distinct users co-collaborate onpage_idwhenever both belong to that page's member set. - Select the user
other_id != target_user_idwho shares the largest count of distinct pages withtarget_user_id, breaking ties by the smallestuser_id(<). - Return
{"target_user_id": target_user_id, "top_collaborator_user_id": best_user, "num_shared_pages": best_count}. If no other user shares a page withtarget_user_id, returnNonefor"top_collaborator_user_id"and0for"num_shared_pages".
- Treat every distinct
"q3"— Highest-rate country (Optional[Dict]):- A user counts as having collaborated if they belong to at least one
page_idthat has2or more distinct accessing users overall (including users absent fromuser_rows). - Across each country present in
user_rows, define:"num_users_in_country": total distinct registered users in that country fromuser_rows(including accounts with zero activity inaccess_rows)."num_users_who_collaborated": how many of those registered users in that country collaborated on at least one multi-user page."collaboration_rate":num_users_who_collaborated / num_users_in_country(afloatin[0.0, 1.0]).
- Return
{"country": best_country, "collaboration_rate": rate, "num_users_in_country": total, "num_users_who_collaborated": active}for the country with the highest"collaboration_rate", breaking exact ties by the lexicographically smallestcountrystring. ReturnNonewhenuser_rowsis empty.
- A user counts as having collaborated if they belong to at least one
Examples
Example 1
Input:
access_rows = [
{'page_id': 'doc_a', 'user_id': 'alice', 'event_ts': '2025-03-10T09:00:00Z', 'is_creator': True, 'collab_source': None},
{'page_id': 'doc_a', 'user_id': 'bob', 'event_ts': '2025-03-10T09:15:00Z', 'is_creator': False, 'collab_source': 'direct_invite'},
{'page_id': 'doc_a', 'user_id': 'bob', 'event_ts': '2025-03-10T10:00:00Z', 'is_creator': False, 'collab_source': 'direct_invite'},
{'page_id': 'doc_b', 'user_id': 'alice', 'event_ts': '2025-03-11T08:00:00Z', 'is_creator': True, 'collab_source': None},
{'page_id': 'doc_b', 'user_id': 'bob', 'event_ts': '2025-03-11T08:30:00Z', 'is_creator': False, 'collab_source': 'shared_url'},
{'page_id': 'doc_b', 'user_id': 'cara', 'event_ts': '2025-03-11T09:00:00Z', 'is_creator': False, 'collab_source': 'shared_url'},
{'page_id': 'doc_c', 'user_id': 'dan', 'event_ts': '2025-03-12T12:00:00Z', 'is_creator': True, 'collab_source': None}
]
user_rows = [
{'user_id': 'alice', 'country': 'DE'},
{'user_id': 'bob', 'country': 'JP'},
{'user_id': 'cara', 'country': 'JP'},
{'user_id': 'dan', 'country': 'DE'}
]
target_user_id = 'alice'
Output:
{
'q1': [
{'collab_source': 'direct_invite', 'num_collaborators': 1, 'pct_of_collaborators': 33.333333333333336},
{'collab_source': 'shared_url', 'num_collaborators': 2, 'pct_of_collaborators': 66.66666666666667}
],
'q2': {'target_user_id': 'alice', 'top_collaborator_user_id': 'bob', 'num_shared_pages': 2},
'q3': {'country': 'JP', 'collaboration_rate': 1.0, 'num_users_in_country': 2, 'num_users_who_collaborated': 2}
}
'bob' opening 'doc_a' twice collapses into one membership, leaving 3 collaborator memberships (1 'direct_invite', 2 'shared_url'). 'alice' co-appears with 'bob' on 'doc_a' and 'doc_b' (2 pages) versus 'cara' on 'doc_b' (1 page). 'dan' only opens 'doc_c' solo, so 'DE' has rate 1/2 = 0.5 while 'JP' has 2/2 = 1.0.
Example 2
Input:
access_rows = [
{'page_id': 101, 'user_id': 50, 'event_ts': '2025-04-01T10:00:00Z', 'is_creator': True, 'collab_source': None},
{'page_id': 101, 'user_id': 30, 'event_ts': '2025-04-01T11:00:00Z', 'is_creator': False, 'collab_source': 'workspace_open'},
{'page_id': 102, 'user_id': 50, 'event_ts': '2025-04-02T10:00:00Z', 'is_creator': True, 'collab_source': None},
{'page_id': 102, 'user_id': 20, 'event_ts': '2025-04-02T11:00:00Z', 'is_creator': False, 'collab_source': 'email_link'}
]
user_rows = [
{'user_id': 20, 'country': 'BR'}, {'user_id': 60, 'country': 'BR'},
{'user_id': 30, 'country': 'AU'}, {'user_id': 70, 'country': 'AU'},
{'user_id': 50, 'country': 'FR'}, {'user_id': 80, 'country': 'FR'}
]
target_user_id = 50
Output:
{
'q1': [
{'collab_source': 'email_link', 'num_collaborators': 1, 'pct_of_collaborators': 50.0},
{'collab_source': 'workspace_open', 'num_collaborators': 1, 'pct_of_collaborators': 50.0}
],
'q2': {'target_user_id': 50, 'top_collaborator_user_id': 20, 'num_shared_pages': 1},
'q3': {'country': 'AU', 'collaboration_rate': 0.5, 'num_users_in_country': 2, 'num_users_who_collaborated': 1}
}
User 50 shares one page each with users 20 and 30; smaller ID 20 breaks the tie. Inactive accounts 60, 70, and 80 stay in their countries' denominators, tying 'AU', 'BR', and 'FR' at 1/2 = 0.5, which 'AU' wins alphabetically.
Constraints
0 <= len(access_rows), len(user_rows) <= 10^5- All
user_idvalues within a single call share a mutually comparable type (strorint), andpage_idvalues are hashable (strorint). event_tsstrings within a call follow a uniform lexicographically sortable UTC format.
Step-by-step walkthrough
Understand the tables and metric rules
We receive two parsed tables (
access_rowsanduser_rows) along withtarget_user_id:access_rows user_rows +---------+---------+----------------------+------------+---------------+ +---------+---------+ | page_id | user_id | event_ts | is_creator | collab_source | | user_id | country | +---------+---------+----------------------+------------+---------------+ +---------+---------+ | doc_a | alice | 2025-03-10T09:00:00Z | True | None | | alice | DE | | doc_a | bob | 2025-03-10T09:15:00Z | False | direct_invite | | bob | JP | | doc_a | bob | 2025-03-10T10:00:00Z | False | direct_invite | | ... | ... | +---------+---------+----------------------+------------+---------------+ +---------+---------+Right away, notice that
'bob'opened'doc_a'twice. Before computing any summary, we apply deduplication (collapsing repeated visits for the same(page_id, user_id)pair into one unique document membership).Here are the exact metric contracts for the three outputs: - Q1 (
q1): Tally unique collaborator memberships — distinct(page_id, user_id)pairs withis_creator = False— grouped bycollab_source. Reportpct_of_collaboratorson a0..100percentage scale, ordered ascending bycollab_source. - Q2 (q2): Both authors and non-authors belong to a page's member set. Find the user (!= target_user_id) who co-appears on the most distinct pages withtarget_user_id, breaking ties by the smallestuser_id. When nobody shares a page with the target, returntop_collaborator_user_id = Noneandnum_shared_pages = 0. - Q3 (q3): Across every country inuser_rows: - Denominator (num_users_in_country): all distinct accounts registered in that country inuser_rows(including inactive accounts with zero page visits). - Numerator (num_users_who_collaborated): registered accounts in that country that appear on at least one page visited by>= 2distinct users overall. - Rate (collaboration_rate):numerator / denominatoron a0..1proportion scale, breaking ties alphabetically bycountry(orNonewhenuser_rowsis empty).Build a page-to-users lookup once
Both Q2 and Q3 ask which distinct users belong to each document. One pass over
access_rowsbuildspages(page_id -> set of distinct user_ids), automatically collapsing repeat visits while keeping both authors and collaborators.from typing import Any, Dict, List, Set def users_by_page(access_rows: List[Dict]) -> Dict[Any, Set[Any]]: """Build page_id -> set of distinct user_ids (both creators and collaborators).""" # pages: e.g. {"doc_a": {"alice", "bob"}, "doc_b": {"alice", "bob", "cara"}} pages: Dict[Any, Set[Any]] = {} for row in access_rows: page_id = row["page_id"] if page_id not in pages: pages[page_id] = set() pages[page_id].add(row["user_id"]) return pagesQ1: deduplicate collaborator channels by earliest visit
Only non-author rows (
is_creator == False) participate in Q1. A collaborator who refreshes a page twenty times joined that page once, so we deduplicate by(page_id, user_id).What if logs contain two collaborator rows for
('doc_a', 'bob')with different channels — say'direct_invite'at09:15and'shared_url'at14:00? Retaining the row with the earliestevent_tsrecords how that collaborator originally gained access. Using strict<(event_ts < earliest_collab[membership_key][0]) preserves log order when two rows share the exact same timestamp, androw["collab_source"] or "unknown"buckets missing channels cleanly.When
access_rowscontains zero collaborator visits,counts_by_sourceis empty, so the final loop skips execution and returns[]without dividing by zero.from typing import Any, Dict, List, Tuple def source_distribution(access_rows: List[Dict]) -> List[Dict]: """Q1: count unique collaborator memberships (page_id, user_id) per collab_source.""" # Phase 1: deduplicate collaborator rows by (page_id, user_id), keeping the earliest visit. # earliest_collab maps (page_id, user_id) -> (earliest_event_ts, source_name). earliest_collab: Dict[Tuple[Any, Any], Tuple[Any, str]] = {} for row in access_rows: if row["is_creator"]: continue membership_key = (row["page_id"], row["user_id"]) source_name = row["collab_source"] or "unknown" event_ts = row["event_ts"] # Strict `<` keeps the earliest timestamp, and on equal timestamps preserves log order. if membership_key not in earliest_collab or event_ts < earliest_collab[membership_key][0]: earliest_collab[membership_key] = (event_ts, source_name) # Phase 2: tally deduplicated memberships per source. counts_by_source: Dict[str, int] = {} for _event_ts, source_name in earliest_collab.values(): counts_by_source[source_name] = counts_by_source.get(source_name, 0) + 1 # Phase 3: convert counts to percentages sorted alphabetically by collab_source. total_memberships = len(earliest_collab) distribution: List[Dict] = [] for source_name in sorted(counts_by_source): count = counts_by_source[source_name] distribution.append({ "collab_source": source_name, "num_collaborators": count, "pct_of_collaborators": 100.0 * count / total_memberships, }) return distributionQ2: count shared pages with the target user
Rather than comparing
target_user_idagainst every user in the directory, inspect each page's member set inpages: - Skip any page wheretarget_user_id not in page_membersinO(1)average time. - On every page containingtarget_user_id, add1toshared_counts[other_user]for eachother_user != target_user_id.Because
page_membersis already aset, each document increments any coworker's count at most once — counting distinct shared pages directly, including pages where two non-author collaborators work together.from typing import Any, Dict, Set def top_collaborator(pages: Dict[Any, Set[Any]], target_user_id: Any) -> Dict: """Q2: find the user sharing the most distinct pages with target_user_id.""" # shared_counts maps other_user_id -> number of distinct pages shared with target_user_id. shared_counts: Dict[Any, int] = {} for page_members in pages.values(): if target_user_id not in page_members: continue for other_user in page_members: if other_user != target_user_id: shared_counts[other_user] = shared_counts.get(other_user, 0) + 1 # Pick highest shared-page count; break ties by smallest user_id. best_user = None best_count = 0 for other_user, shared_pages in shared_counts.items(): if ( best_user is None or shared_pages > best_count or (shared_pages == best_count and other_user < best_user) ): best_user = other_user best_count = shared_pages return { "target_user_id": target_user_id, "top_collaborator_user_id": best_user, "num_shared_pages": best_count, }Q3: find the country with the highest collaboration rate
How do we identify every user who collaborated without enumerating pairs of users? Check the cardinality of each page's member set: - When
len(page_members) == 1(like'doc_c'in Example 1), that user worked solo on that document. - Whenlen(page_members) >= 2, every member ofpage_membersshared that document with at least one other distinct person!One linear scan over
pagespopulatescollaborated_userswith zeroO(k^2)pair blowup on widely read documents.Next, map
user_rowsintocountry_by_userand tallytotal_in_countryandcollab_in_country. Accounts appearing only inaccess_rowswithout auser_rowsrecord still help makelen(page_members) >= 2while being omitted from country totals.To compare rates
collab_count / total_countvsbest_collab / best_totalwithout floating-point rounding drift (such as1/3vs2/6), cross-multiplycollab_count * best_totalagainstbest_collab * total_countusing exact integer arithmetic!from typing import Any, Dict, List, Optional, Set def top_country(pages: Dict[Any, Set[Any]], user_rows: List[Dict]) -> Optional[Dict]: """Q3: find the country with the highest collaboration rate among its registered users.""" # Phase 1: a user collaborated iff they appear on at least one page with >= 2 distinct users. collaborated_users: Set[Any] = set() for page_members in pages.values(): if len(page_members) >= 2: collaborated_users.update(page_members) # Phase 2: map each user_id in user_rows to their country (deduplicating user_rows if needed). country_by_user: Dict[Any, str] = {} for row in user_rows: country_by_user[row["user_id"]] = row["country"] # Phase 3: count total users (denominator) and collaborating users (numerator) per country. total_in_country: Dict[str, int] = {} collab_in_country: Dict[str, int] = {} for user_id, country in country_by_user.items(): total_in_country[country] = total_in_country.get(country, 0) + 1 if user_id in collaborated_users: collab_in_country[country] = collab_in_country.get(country, 0) + 1 # Phase 4: select the top country; compare collab/total via exact integer cross-multiplication # (a/b > c/d <=> a*d > c*b for positive denominators) and break ties alphabetically. best_country: Optional[str] = None best_collab = 0 best_total = 1 for country, total_count in total_in_country.items(): collab_count = collab_in_country.get(country, 0) if best_country is None: best_country = country best_collab = collab_count best_total = total_count continue lhs = collab_count * best_total rhs = best_collab * total_count if lhs > rhs or (lhs == rhs and country < best_country): best_country = country best_collab = collab_count best_total = total_count if best_country is None: return None return { "country": best_country, "collaboration_rate": best_collab / best_total, "num_users_in_country": best_total, "num_users_who_collaborated": best_collab, }Trace Example 1 end to end
Walk through
analyze_document_collaborationon Example 1 (target_user_id = 'alice'):Step 1 — users_by_page(access_rows): 'doc_a' -> {'alice', 'bob'} (bob's two visits collapse into one set entry) 'doc_b' -> {'alice', 'bob', 'cara'} 'doc_c' -> {'dan'} (solo page: size 1) Step 2 — Q1 source_distribution: Collaborator memberships (is_creator == False): ('doc_a', 'bob') -> 'direct_invite' ('doc_b', 'bob') -> 'shared_url' ('doc_b', 'cara') -> 'shared_url' Total = 3 -> 'direct_invite': 1 (33.33%), 'shared_url': 2 (66.67%) Step 3 — Q2 top_collaborator for 'alice': 'doc_a' contains 'alice' -> shared_counts['bob'] = 1 'doc_b' contains 'alice' -> shared_counts['bob'] = 2, shared_counts['cara'] = 1 Highest count wins -> 'bob' (num_shared_pages = 2) Step 4 — Q3 top_country: 'doc_a' (size 2) and 'doc_b' (size 3) have >= 2 users -> collaborated_users = {'alice', 'bob', 'cara'} 'DE' users: alice (yes), dan (no) -> 1 / 2 = 0.5 'JP' users: bob (yes), cara (yes) -> 2 / 2 = 1.0 Highest rate wins -> 'JP' (rate 1.0, 2 in country, 2 collaborated)from typing import Any, Dict, List def analyze_document_collaboration( access_rows: List[Dict], user_rows: List[Dict], target_user_id: Any ) -> Dict: pages = users_by_page(access_rows) return { "q1": source_distribution(access_rows), "q2": top_collaborator(pages, target_user_id), "q3": top_country(pages, user_rows), }Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def users_by_page(access_rows: List[Dict]) -> Dict[Any, Set[Any]]: """Build page_id -> set of distinct user_ids (both creators and collaborators).""" # pages: e.g. {"doc_a": {"alice", "bob"}, "doc_b": {"alice", "bob", "cara"}} pages: Dict[Any, Set[Any]] = {} for row in access_rows: page_id = row["page_id"] if page_id not in pages: pages[page_id] = set() pages[page_id].add(row["user_id"]) return pages def source_distribution(access_rows: List[Dict]) -> List[Dict]: """Q1: count unique collaborator memberships (page_id, user_id) per collab_source.""" # Phase 1: deduplicate collaborator rows by (page_id, user_id), keeping the earliest visit. # earliest_collab maps (page_id, user_id) -> (earliest_event_ts, source_name). earliest_collab: Dict[Tuple[Any, Any], Tuple[Any, str]] = {} for row in access_rows: if row["is_creator"]: continue membership_key = (row["page_id"], row["user_id"]) source_name = row["collab_source"] or "unknown" event_ts = row["event_ts"] # Strict `<` keeps the earliest timestamp, and on equal timestamps preserves log order. if membership_key not in earliest_collab or event_ts < earliest_collab[membership_key][0]: earliest_collab[membership_key] = (event_ts, source_name) # Phase 2: tally deduplicated memberships per source. counts_by_source: Dict[str, int] = {} for _event_ts, source_name in earliest_collab.values(): counts_by_source[source_name] = counts_by_source.get(source_name, 0) + 1 # Phase 3: convert counts to percentages sorted alphabetically by collab_source. total_memberships = len(earliest_collab) distribution: List[Dict] = [] for source_name in sorted(counts_by_source): count = counts_by_source[source_name] distribution.append({ "collab_source": source_name, "num_collaborators": count, "pct_of_collaborators": 100.0 * count / total_memberships, }) return distribution def top_collaborator(pages: Dict[Any, Set[Any]], target_user_id: Any) -> Dict: """Q2: find the user sharing the most distinct pages with target_user_id.""" # shared_counts maps other_user_id -> number of distinct pages shared with target_user_id. shared_counts: Dict[Any, int] = {} for page_members in pages.values(): if target_user_id not in page_members: continue for other_user in page_members: if other_user != target_user_id: shared_counts[other_user] = shared_counts.get(other_user, 0) + 1 # Pick highest shared-page count; break ties by smallest user_id. best_user = None best_count = 0 for other_user, shared_pages in shared_counts.items(): if ( best_user is None or shared_pages > best_count or (shared_pages == best_count and other_user < best_user) ): best_user = other_user best_count = shared_pages return { "target_user_id": target_user_id, "top_collaborator_user_id": best_user, "num_shared_pages": best_count, } def top_country(pages: Dict[Any, Set[Any]], user_rows: List[Dict]) -> Optional[Dict]: """Q3: find the country with the highest collaboration rate among its registered users.""" # Phase 1: a user collaborated iff they appear on at least one page with >= 2 distinct users. collaborated_users: Set[Any] = set() for page_members in pages.values(): if len(page_members) >= 2: collaborated_users.update(page_members) # Phase 2: map each user_id in user_rows to their country (deduplicating user_rows if needed). country_by_user: Dict[Any, str] = {} for row in user_rows: country_by_user[row["user_id"]] = row["country"] # Phase 3: count total users (denominator) and collaborating users (numerator) per country. total_in_country: Dict[str, int] = {} collab_in_country: Dict[str, int] = {} for user_id, country in country_by_user.items(): total_in_country[country] = total_in_country.get(country, 0) + 1 if user_id in collaborated_users: collab_in_country[country] = collab_in_country.get(country, 0) + 1 # Phase 4: select the top country; compare collab/total via exact integer cross-multiplication # (a/b > c/d <=> a*d > c*b for positive denominators) and break ties alphabetically. best_country: Optional[str] = None best_collab = 0 best_total = 1 for country, total_count in total_in_country.items(): collab_count = collab_in_country.get(country, 0) if best_country is None: best_country = country best_collab = collab_count best_total = total_count continue lhs = collab_count * best_total rhs = best_collab * total_count if lhs > rhs or (lhs == rhs and country < best_country): best_country = country best_collab = collab_count best_total = total_count if best_country is None: return None return { "country": best_country, "collaboration_rate": best_collab / best_total, "num_users_in_country": best_total, "num_users_who_collaborated": best_collab, } def analyze_document_collaboration( access_rows: List[Dict], user_rows: List[Dict], target_user_id: Any ) -> Dict: pages = users_by_page(access_rows) return { "q1": source_distribution(access_rows), "q2": top_collaborator(pages, target_user_id), "q3": top_country(pages, user_rows), }✅ Submit now — all tests should pass.
Intuition & how it works
Picture access_rows as an office badge-swipe log and each page_id as a project room. When 'bob' badges into room 'doc_a' twice in one morning, 'bob' didn't join two separate projects — 'bob' is still one member of 'doc_a'. Everything starts with deduplication (collapsing repeated visits for the same (page_id, user_id) pair into a single document membership). Once raw events are condensed into an attendance set per page (page_id -> set of unique user_ids), all three summaries reduce to fast linear passes.
Skipping deduplication or comparing raw rows pairwise fails in both correctness and runtime. Counting raw log rows overweights heavy tab-refreshers, while scanning pairs of access rows costs O(R^2) time — and materializing all user pairs on a 10,000-reader company memo creates 10^8 pairs for Q3 when simply checking len(page_members) >= 2 marks every collaborating member in O(1) time per user.
Walk through Example 1 (target_user_id = 'alice'):
1. Collapse visits per page: 'doc_a' has {'alice', 'bob'} ('bob''s repeat visit collapses), 'doc_b' has {'alice', 'bob', 'cara'}, and 'doc_c' has {'dan'}.
2. Q1 (collaborator channels): keeping is_creator = False memberships leaves ('doc_a', 'bob') -> 'direct_invite', ('doc_b', 'bob') -> 'shared_url', and ('doc_b', 'cara') -> 'shared_url' -> 'direct_invite' is 1/3 = 33.33% and 'shared_url' is 2/3 = 66.67%.
3. Q2 (top co-collaborator for 'alice'): 'alice' shares 'doc_a' and 'doc_b' with 'bob' (2 pages) versus only 'doc_b' with 'cara' (1 page), picking 'bob'.
4. Q3 (highest-rate country): 'doc_a' and 'doc_b' have >= 2 members while 'doc_c' is solo ('dan'), giving 'JP' 2/2 = 1.0 ahead of 'DE' at 1/2 = 0.5.
Complexity
Let R = len(access_rows), U = len(user_rows), M <= R be the count of unique (page_id, user_id) memberships, P <= M be the count of distinct pages, and C be the count of distinct collab_source names.
users_by_page—O(R)time,O(M)space: visits each of theRevents once withO(1)average hash-set insertion, storingMunique(page, user)memberships across page sets.- Q1 (
source_distribution) —O(R + C log C)time,O(M)space: scansRevents once to record earliest channels for up toMcollaborator memberships, aggregates counts inO(M)time, and sortsCchannel strings inO(C log C)time. - Q2 (
top_collaborator) —O(M)worst-case time,O(U)space: teststarget_user_id in page_membersinO(1)time acrossPpages and iterates over members only on pages containing the target (at mostMtotal entries). - Q3 (
top_country) —O(M + U)time,O(M + U)space: scans page sets (O(M)total items) to mark collaborating accounts, scansUdirectory rows to compute per-country totals, and picks the maximum in one pass over countries. - Overall —
O(R + U + C log C)time andO(M + U)space.
Edge cases
- Repeated visits to the same document: collapsed into one
(page_id, user_id)membership across Q1, Q2, and Q3. - Changing
collab_sourceacross visits: Q1 attributes the membership to its earliestevent_ts(breaking timestamp ties by log order via strict<). Noneor emptycollab_sourceon a collaborator event: grouped under"unknown"so percentages sum to100%.- Zero collaborator visits (or empty
access_rows): Q1 returns[]without dividing by zero. - Target user absent or only on solo pages: Q2 returns
top_collaborator_user_id = Noneandnum_shared_pages = 0. - Inactive accounts in
user_rows: accounts with zero visits (such as60,70,80in Example 2) still count in their country's denominatornum_users_in_country. - Visiting accounts absent from
user_rows: still count in Q1, Q2, and toward makinglen(page_members) >= 2in Q3, while having no country bucket in Q3. - Empty
user_rows: Q3 returnsNone. - Loading raw CSV strings in production:
csv.DictReaderyields"FALSE"as a non-empty truthystr, so normalizerow["is_creator"].strip().upper() == "TRUE"when parsing text files directly.
Common mistakes
- Tallying raw events rather than deduplicated
(page_id, user_id)pairs: inflates Q1 channel counts and Q2 shared-page totals whenever a user reopens a document. - Allowing
target_user_idto match itself in Q2: omittingother_user != target_user_idmakes the target user win against real coworkers. - Pairing only authors with non-authors in Q2: two non-author collaborators on the same page (
'bob'and'cara'on'doc_b') also co-collaborated with each other. - Omitting page authors from Q3's numerator: Example 2 confirms that user
50(who only authored pages) counts as having collaborated once other users joined those pages. - Restricting Q3's denominator to active log users: omits inactive registered accounts in
user_rowsand computes a different ratio. - Confusing
0..100vs0..1scales: Q1 reports percentages on0..100(33.333...), whereas Q3 reports proportions on0..1(0.5,1.0).
Alternative approaches
In SQL interviews, Q2 and Q3 map cleanly to a CTE (Common Table Expression — a named temporary query block introduced with WITH) and a self-join (joining a table to itself on page_id to pair co-members):
-- Q2: top co-collaborator for :target_user_id
WITH memberships AS (
SELECT DISTINCT page_id, user_id
FROM doc_access
)
SELECT
other.user_id AS top_collaborator_user_id,
COUNT(*) AS num_shared_pages
FROM memberships AS target
JOIN memberships AS other
ON target.page_id = other.page_id
AND target.user_id <> other.user_id
WHERE target.user_id = :target_user_id
GROUP BY other.user_id
ORDER BY num_shared_pages DESC, other.user_id ASC
LIMIT 1;
-- Q3: highest-rate country (LEFT JOIN retains inactive registered users in the denominator)
WITH memberships AS (
SELECT DISTINCT page_id, user_id
FROM doc_access
),
collaborated_users AS (
SELECT DISTINCT user_id
FROM memberships
WHERE page_id IN (
SELECT page_id
FROM memberships
GROUP BY page_id
HAVING COUNT(*) >= 2
)
)
SELECT
u.country,
1.0 * COUNT(c.user_id) / COUNT(*) AS collaboration_rate,
COUNT(*) AS num_users_in_country,
COUNT(c.user_id) AS num_users_who_collaborated
FROM users AS u
LEFT JOIN collaborated_users AS c
ON u.user_id = c.user_id
GROUP BY u.country
ORDER BY collaboration_rate DESC, u.country ASC
LIMIT 1;
Follow-up questions
- How can you prevent countries with tiny user counts from dominating the collaboration-rate leaderboard? A simple product rule enforces a minimum denominator cutoff (for instance, considering only countries with at least
100registered users). A smoother statistical solution uses Bayesian shrinkage (blending noisy small-sample ratios toward the global mean via prior pseudo-counts), ranking by(collaborated + m * global_rate) / (total + m)wherem(e.g.,50) sets the strength of the prior. Alternatively, rank countries by the lower bound of a confidence interval (a range of plausible true rates for a given sample size, such as a 95% Wilson score lower bound) so a1/1country cannot beat a999/1000country. - What changes if ties for the top co-collaborator should be broken by the most recent shared activity rather than smallest user ID? Track
latest_visit[(page_id, user_id)] = max(event_ts)per membership instead of a bare user set. On each document shared betweentarget_user_idandother_user, define their shared-activity timestamp on that document — such asmin(latest_visit[page, target], latest_visit[page, other])(the earliest point by which both had visited) ormax(...)(most recent visit by either member) — and maintainlast_shared_ts[other_user]as the maximum across their shared pages. Candidates can then be compared by(shared_pages, last_shared_ts)descending. - How would you execute these three aggregations efficiently across billions of log rows in a distributed data warehouse? Deduplicate first with
GROUP BY page_id, user_id(computingMIN_BY(collab_source, event_ts)on non-author rows), which typically shrinks raw event volume by10x–100x. From that compact membership table, Q1 and Q3 (COUNTper page followed by a hash/broadcast join tousers) finish in linearO(M + U)distributed scans. Computing Q2 for all users at once is the only quadratic risk because a10,000-viewer company-wide page produces~10^8pairs in a self-join; in practice, filter out giant broadcast documents (e.g.,> 500viewers) since viewing an all-hands announcement does not represent 1-on-1 collaboration.
Follow-up questions
- How can you prevent countries with tiny user counts from dominating the collaboration-rate leaderboard?
- What changes if ties for the top co-collaborator should be broken by the most recent shared activity rather than smallest user ID?
- How would you execute these three aggregations efficiently across billions of log rows in a distributed data warehouse?
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 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