Co-Access Analytics on Document Usage Logs
SQL & DataAuto-graded · 15 test casesLast updated
Tests data deduplication, self-joins, metric definition, and grouped aggregation over access logs with user metadata.
You are building analytics for a document platform. You receive two lists of records representing document access events and user profiles.
Input Data
1. access_log (list of dictionaries)
Each dictionary represents one access event when a user opened or viewed a document page.
| Field | Type | Description |
|---|---|---|
page_id | string or int | Identifier of the document page |
user_id | string or int | Identifier of the user who accessed it |
event_ts | string | Timestamp of the access event (UTC) |
is_creator | bool | True if this user created/owns the document, False otherwise |
collab_source | string or None | For non-creators only: how the user gained access (e.g., "invited", "link share", "org default"). May be None or empty. |
Notes:
- The same user may access the same page multiple times, producing duplicate
(page_id, user_id)entries. - Unless otherwise stated, treat access at the page membership level: deduplicate to unique
(page_id, user_id)pairs. - A user with
is_creator=Trueis considered a participant on that page.
2. user_list (list of dictionaries)
Each dictionary contains profile information for a user.
| Field | Type | Description |
|---|---|---|
user_id | string or int | User identifier |
country | string | Country code or name for the user |
3. focus_user (string or int)
A user identifier for which you will compute a specific statistic in part 2.
Tasks
Return a dictionary with three keys: 'q1', 'q2', and 'q3', each containing the result of one task below.
Task 1: Source Distribution for Non-Creator Access
For all non-creator access (is_creator=False), compute how many unique (page_id, user_id) memberships exist for each collab_source value (ignoring None or empty sources).
Output (value of 'q1' key): A list of dictionaries, sorted alphabetically by collab_source, each containing:
collab_source(string): the source valuenum_collaborators(int): count of unique(page_id, user_id)pairs with this sourcepct_of_collaborators(float): percentage this source represents out of all non-creator memberships with a source (0–100 scale)
If there are no non-creator memberships with sources, return an empty list.
Task 2: Most Frequent Co-Participant for a Given User
Find which other user appears on the most pages in common with focus_user.
Define co-participation as: both users have at least one access record on the same page_id (after deduplication to unique memberships).
Output (value of 'q2' key): A dictionary containing:
target_user_id: thefocus_uservalue passed intop_collaborator_user_id: the other user with the highest count of shared pages, orNoneif no co-participants existnum_shared_pages(int): the number of distinct pages both users appear on
Tie-breaking: If multiple users tie for the maximum number of shared pages, return the one with the smallest user_id (lexicographically for strings, numerically for integers).
Task 3: Country with Highest Co-Participation Rate
Determine which country has the highest fraction of its users who co-participated with at least one other distinct user.
Metric definition:
- Numerator: Count of users in the country who appear on at least one page that has two or more distinct users (i.e., they shared a page with someone else).
- Denominator: Total count of users in the country according to
user_list. - Rate: Numerator divided by denominator (return as a decimal between 0 and 1).
Users in access_log but not in user_list have no country and are excluded. Users in user_list who never accessed any page contribute to the denominator but not the numerator.
Output (value of 'q3' key): A dictionary containing:
country(string or None): the country with the highest rate, orNoneifuser_listis emptycollaboration_rate(float): the rate (0–1), or -1 if no country existsnum_users_in_country(int): total users in that countrynum_users_who_collaborated(int): users in that country who co-participated
Tie-breaking: Highest rate first; if tied, choose the country that is smallest alphabetically.
Constraints
- 0 ≤ len(access_log) ≤ 10⁵
- 0 ≤ len(user_list) ≤ 10⁴
- All
page_idanduser_idvalues are hashable (strings or integers). collab_sourcemay beNone, an empty string, or a non-empty string.focus_usermay or may not appear inaccess_log.
Examples
Example 1
Input: compute_access_analytics([{'page_id': 'p1', 'user_id': 'u1', 'event_ts': '2024-01-01T00:00:00Z', 'is_creator': True, 'collab_source': None}, {'page_id': 'p1', 'user_id': 'u2', 'event_ts': '2024-01-01T01:00:00Z', 'is_creator': False, 'collab_source': 'invited'}, {'page_id': 'p1', 'user_id': 'u2', 'event_ts': '2024-01-01T02:00:00Z', 'is_creator': False, 'collab_source': 'invited'}, {'page_id': 'p2', 'user_id': 'u1', 'event_ts': '2024-01-02T00:00:00Z', 'is_creator': True, 'collab_source': None}, {'page_id': 'p2', 'user_id': 'u3', 'event_ts': '2024-01-02T01:00:00Z', 'is_creator': False, 'collab_source': 'link share'}, {'page_id': 'p2', 'user_id': 'u4', 'event_ts': '2024-01-02T02:00:00Z', 'is_creator': False, 'collab_source': 'link share'}], [{'user_id': 'u1', 'country': 'US'}, {'user_id': 'u2', 'country': 'CA'}, {'user_id': 'u3', 'country': 'CA'}, {'user_id': 'u4', 'country': 'US'}], 'u1')
Output: {'q1': [{'collab_source': 'invited', 'num_collaborators': 1, 'pct_of_collaborators': 33.33333333333333}, {'collab_source': 'link share', 'num_collaborators': 2, 'pct_of_collaborators': 66.66666666666666}], 'q2': {'target_user_id': 'u1', 'top_collaborator_user_id': 'u2', 'num_shared_pages': 1}, 'q3': {'country': 'CA', 'collaboration_rate': 1, 'num_users_in_country': 2, 'num_users_who_collaborated': 2}}
Example 2
Input: compute_access_analytics([{'page_id': 1, 'user_id': 10, 'event_ts': '2024-02-01', 'is_creator': True, 'collab_source': None}, {'page_id': 1, 'user_id': 20, 'event_ts': '2024-02-01', 'is_creator': False, 'collab_source': 'org default'}, {'page_id': 2, 'user_id': 10, 'event_ts': '2024-02-02', 'is_creator': True, 'collab_source': None}, {'page_id': 2, 'user_id': 30, 'event_ts': '2024-02-02', 'is_creator': False, 'collab_source': 'invited'}, {'page_id': 3, 'user_id': 20, 'event_ts': '2024-02-03', 'is_creator': True, 'collab_source': None}], [{'user_id': 10, 'country': 'US'}, {'user_id': 20, 'country': 'US'}, {'user_id': 30, 'country': 'GB'}, {'user_id': 40, 'country': 'GB'}], 20)
Output: {'q1': [{'collab_source': 'invited', 'num_collaborators': 1, 'pct_of_collaborators': 50}, {'collab_source': 'org default', 'num_collaborators': 1, 'pct_of_collaborators': 50}], 'q2': {'target_user_id': 20, 'top_collaborator_user_id': 10, 'num_shared_pages': 1}, 'q3': {'country': 'US', 'collaboration_rate': 1, 'num_users_in_country': 2, 'num_users_who_collaborated': 2}}
Hints
Hint 1
Deduplicate access_log to unique (page_id, user_id) pairs first; all three tasks rely on this membership set.
Hint 2
For task 2, build a mapping from each page to its set of users, then count how many of the focus_user's pages contain each other user.
Hint 3
For task 3, a user has co-participated if they belong to any page with at least two distinct members; avoid building all pairs explicitly.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The three tasks all operate on the same underlying membership data, so we normalize once upfront and then answer each question from shared structures.
Step 1: Deduplicate to unique memberships
Scan access_log and build:
- A set of unique
(page_id, user_id)pairs. Both creators and non-creators are members. - A dictionary mapping
(page_id, user_id)tocollab_source, containing only non-creator memberships with a non-empty source. If the same pair appears multiple times with different sources, the last one seen wins (though in practice test cases avoid this ambiguity).
Step 2: Answer each task
-
Task 1: Count how many memberships exist for each
collab_source, compute percentages out of the total, and sort alphabetically. If the total is zero, return an empty list. -
Task 2: Build a reverse index from each page to the set of users on it. Find all pages the
focus_userappears on, then for each of those pages, increment a counter for every other user on the page. The user with the highest count is the answer; ties are broken by choosing the smallestuser_id. If no co-participants exist, returnNoneand0. -
Task 3: A user has co-participated if they belong to at least one page with two or more distinct members. Build a page-to-users mapping, then for every page with multiple users, record pairwise co-participation relationships (or simply mark each member as having co-participated). Count how many users in each country co-participated, divide by the total users in that country from
user_list, and pick the country with the highest rate (ties broken alphabetically).
Why It Works
- Deduplication ensures repeated accesses by the same user on the same page don't inflate counts.
- In task 2, each page the focus user is on contributes exactly 1 to the shared-page count with each other user on that page, which matches the definition of "number of distinct shared pages."
- In task 3, the pairwise expansion for pages with k users correctly identifies all users who have at least one co-participant. The denominator includes all users from
user_list, including those who never accessed any page, which makes the rate a true fraction of the country's user base.
Complexity
Let R = number of records in access_log, M = number of unique (page_id, user_id) memberships, U = number of users in user_list, and P = number of distinct pages.
- Time: O(R) to deduplicate and build structures. Task 1 is O(M). Task 2 is O(M) (iterating memberships and users per page). Task 3 is O(M × k) where k is the average page size for the pairwise step, plus O(U) for the country aggregation. Overall O(R + M × k + U).
- Space: O(M + U) for the membership set, page-to-users mapping, user-country lookup, and result structures.
Reference Solution
from collections import defaultdict
from typing import Dict, List
def compute_access_analytics(access_log: List[Dict], user_list: List[Dict], focus_user) -> Dict:
# Build user-to-country lookup
user_country = {u['user_id']: u['country'] for u in user_list}
# Deduplicate to unique (page_id, user_id) memberships
page_users = set()
collab_sources = {}
for record in access_log:
page_id = record['page_id']
user_id = record['user_id']
is_creator = record['is_creator']
collab_source = record['collab_source']
page_users.add((page_id, user_id))
# Track collab_source for non-creators with non-empty source
if not is_creator and collab_source:
collab_sources[(page_id, user_id)] = collab_source
# Task 1: Distribution of non-creator sources
source_counts = defaultdict(int)
for (page_id, user_id), source in collab_sources.items():
source_counts[source] += 1
total_collabs = sum(source_counts.values())
q1_result = []
for source, count in sorted(source_counts.items()):
pct = (count / total_collabs * 100) if total_collabs > 0 else 0
q1_result.append({
'collab_source': source,
'num_collaborators': count,
'pct_of_collaborators': pct
})
# Task 2: Top co-participant for focus_user
# Build page -> users mapping
page_to_users = defaultdict(set)
for page_id, user_id in page_users:
page_to_users[page_id].add(user_id)
# Count shared pages with focus_user
collab_counts = defaultdict(int)
focus_pages = {page_id for page_id, user_id in page_users if user_id == focus_user}
for page_id in focus_pages:
for user_id in page_to_users[page_id]:
if user_id != focus_user:
collab_counts[user_id] += 1
# Find top co-participant (tie-break by smallest user_id)
top_collaborator = None
max_shared = 0
if collab_counts:
max_shared = max(collab_counts.values())
candidates = [uid for uid, count in collab_counts.items() if count == max_shared]
top_collaborator = min(candidates)
q2_result = {
'target_user_id': focus_user,
'top_collaborator_user_id': top_collaborator,
'num_shared_pages': max_shared
}
# Task 3: Country with highest co-participation rate
# Identify users who co-participated (appear on page with 2+ members)
user_collaborators = defaultdict(set)
for page_id in page_to_users:
users_on_page = list(page_to_users[page_id])
if len(users_on_page) >= 2:
for i, u1 in enumerate(users_on_page):
for u2 in users_on_page[i+1:]:
user_collaborators[u1].add(u2)
user_collaborators[u2].add(u1)
# Count total users per country and those who co-participated
country_total = defaultdict(int)
country_collab = defaultdict(int)
for user_id, country in user_country.items():
country_total[country] += 1
if len(user_collaborators[user_id]) > 0:
country_collab[country] += 1
# Compute collaboration rate per country
best_country = None
best_rate = -1
for country in country_total:
rate = country_collab[country] / country_total[country] if country_total[country] > 0 else 0
if rate > best_rate or (rate == best_rate and (best_country is None or country < best_country)):
best_rate = rate
best_country = country
q3_result = {
'country': best_country,
'collaboration_rate': best_rate,
'num_users_in_country': country_total[best_country] if best_country else 0,
'num_users_who_collaborated': country_collab[best_country] if best_country else 0
}
return {
'q1': q1_result,
'q2': q2_result,
'q3': q3_result
}