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

  1. 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): True when this viewer is the author who created page_id, False otherwise.
    • 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).
  2. 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]: Parse document_activity.csv into dictionaries with keys "page_id", "user_id", "viewed_at" (normalized to a timezone-aware UTC datetime), "is_creator" (True for "true", "t", "1", or "yes" in any case; False otherwise), and "collaborator_source" (None when blank or "NULL", otherwise stripped text).
  • read_users(file: IO[str]) -> List[dict]: Parse users.csv into 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 with is_creator=True is the page's author and must never be counted as a collaborator on that page_id, even if another row for the same pair logs is_creator=False.
    • Attribute each remaining (page_id, user_id) pair to the channel from its earliest UTC viewed_at event (substituting "unknown" when collaborator_source is None; 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 where collaborator_share is collaborator_count / total_collaborator_pairs, ordered by collaborator_count descending and then collaborator_source ascending (or [] when no collaborator pairs exist).
  • 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_id at least once (including page creators).
    • Count distinct shared page_ids between target_user_id and 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 highest shared_page_count (>= 1), sorted ascending by co_user_id. Return [] if target_user_id has no shared pages.
  • country_collaboration_rates(activity: List[dict], users: List[dict]) -> List[dict]:
    • A user counts as collaborating if at least one page_id they viewed has 2 or more distinct user_ids across activity (even if another viewer on that page is absent from users).
    • For each country in users, compute total_users (distinct user_ids in users for that country, including accounts with zero page views), collaborating_users (how many of those country users collaborated), and collaboration_rate = collaborating_users / total_users.
    • Return {"country": str, "collaborating_users": int, "total_users": int, "collaboration_rate": float} ordered by collaboration_rate descending and then country ascending.

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_at values inside activity dictionaries passed directly to the metric functions may be either timezone-aware/naive UTC datetime objects or ISO-8601 UTC timestamp strings.
  • Floating-point outputs (collaborator_share and collaboration_rate) are compared within 1e-9 tolerance.
  • Empty inputs must be handled without division-by-zero errors (collaborator_source_distribution([]) == [], top_collaborators([], target) == [], and country_collaboration_rates([], users) reports 0.0 for each country in users).

Step-by-step walkthrough

  1. 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:

    1. Multiple views with different sources (Task 1): User ben might first open page doc-10 via "slack_share" at 14:03 and reopen it via "bookmark" at 14:09. Counting (doc-10, ben) under both sources would make shares exceed 100%. We use first-touch attribution: each collaborator pair gets the source of its earliest view timestamp (breaking exact timestamp ties alphabetically by source name).
    2. Missing collaborator_source on a non-creator (Task 1): We map NULL / empty strings to "unknown" instead of dropping the pair, so every true collaborator stays in the denominator and shares sum to 1.0.
    3. Creators are never collaborators on their own page (Task 1): Even if a messy log row records is_creator = false for the page's creator on a later reload, that (page_id, user_id) pair is still the creator and is excluded from Task 1.
    4. Who counts as collaborating on a page (Tasks 2 & 3): Both creators and non-creators count as viewers of a page. If page doc-10 has {ava (creator), ben (viewer)}, both ava and ben collaborated on doc-10.
    5. Country denominator and unmapped users (Task 3): total_users comes from users.csv (so signed-up users with zero views still count in the denominator with 0 collaborations). Conversely, if a guest viewer missing from users.csv views page spec-1 alongside u10, page spec-1 still has 2 distinct users so u10 collaborated, while the unmapped guest belongs to no country bucket.
  2. Parse CSV files cleanly at the boundary

    CSV files deliver every column as a raw string, so read_activity and read_users convert types once at ingestion:

    • Booleans: Never write bool(raw["is_creator"]) — in Python, bool("false") evaluates to True because any non-empty string is truthy! Check raw["is_creator"].strip().lower() in ("true", "t", "1", "yes").
    • Null sources: Convert "" and "NULL" (case-insensitive) to None.
    • UTC timestamps: Normalize trailing "Z" to "+00:00", parse with datetime.fromisoformat, and attach or convert to timezone.utc so "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
    
  3. 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 activity into a dictionary page_id -> set of distinct user_ids deduplicates repeated views in a single O(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_page
    
  4. Task 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:

    1. Collect creator_pairs: Scan all rows first to find every (page_id, user_id) with is_creator == True. Doing this in a separate first pass ensures we recognize a creator even if their is_creator = True row appears after an is_creator = False row in an unsorted file.
    2. Find each pair's earliest view: For every row not in creator_pairs, build candidate = (_to_utc_datetime(row["viewed_at"]), source) and keep the minimum tuple per (page_id, user_id).
    3. Aggregate and compute shares: Count how many distinct pairs landed in each source, divide by total_pairs = len(first_view), and sort by (-collaborator_count, collaborator_source). If first_view is empty, counts is 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
    
  5. 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, add 1 to shared_counts[user_id] for each other user on that page (user_id != target_user_id). Because users_on_page is already a set, each shared page adds 1 regardless of view count.
    • If shared_counts is empty (the target never viewed a page, or only viewed solo pages), return []. Otherwise find max_shared = max(shared_counts.values()) and return all tied co-users in sorted co_user_id order.
    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
    
  6. Task 3: country-level collaboration rates

    A user has "collaborated with others" if at least one page they viewed has 2 or more distinct users in total:

    1. Find all collaborating users: Loop over _users_by_page(activity). Whenever len(users_on_page) >= 2, add everyone in users_on_page to collaborating_user_ids.
    2. Group users.csv by country: Build users_by_country[country] = set_of_distinct_user_ids from users. Using a set protects against duplicate rows in users.csv, and starting from users preserves inactive users in total_users.
    3. Compute rates and rank: For each country, count how many of its country_user_ids belong to collaborating_user_ids, divide by len(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
    
  7. 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 of 5 pairs: slack_share has 2 (0.4), and bookmark, mention_email, workspace_search each have 1 (0.2).
    • Task 2 (target_user_id = "ava"): ava appears on doc-10 (with ben, cora), doc-20 (with ben, cora), and doc-30 (with dev). 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, giving collaborating_user_ids = {ava, ben, cora, dev}.
      • JP has {ava, ben, finn} (finn never viewed anything): 2 / 3 ≈ 0.667.
      • GB has {cora, dev, eli, gina} (eli only viewed solo page doc-40, gina inactive): 2 / 4 = 0.5.
      • JP ranks ahead of GB.
  8. 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 the E events build creator_pairs and first_view using O(1) expected dictionary lookups per row, one pass over P pairs tallies counts per source, and sorting the handful of S source buckets (S <= P) finishes the output.
  • Task 2 (top_collaborators) — O(E + K log K) time, O(P) space where K is the number of distinct co-users of the target: One O(E) pass builds _users_by_page (O(P) stored user-page entries across all sets), scanning pages containing target_user_id touches at most P entries, and sorting the K co-user IDs takes O(K log K).
  • Task 3 (country_collaboration_rates) — O(E + U + C log C) time, O(P + U) space: One O(E) pass builds _users_by_page and collects collaborating_user_ids, one O(U) pass groups users into per-country user sets, and sorting the C country summaries takes O(C log C).

Edge cases

  • Repeated views of the same page: Collapsed by set membership in Tasks 2 & 3 and by first_view dictionary 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 UTC datetime objects before comparison so "08:00Z" beats "09:30" even though ASCII ' ' sorts before 'T'.
  • Missing or "NULL" collaborator_source on a non-creator: Bucketed as "unknown" rather than dropped, keeping all shares honest and summing to 1.0.
  • Creator logged again with is_creator = False: Caught by the first-pass creator_pairs set 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 reports 0 collaborating users and 0.0 rate for every country in users.csv.
  • Co-viewer missing from users.csv: Determining whether a page has >= 2 users before joining to users ensures 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_shared sorted by co_user_id; Task 3 breaks equal collaboration rates alphabetically by country.

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 NULL collaborator sources in Task 1: Filtering WHERE collaborator_source IS NOT NULL shrinks the denominator and overstates every remaining channel's share.
  • Using an INNER JOIN on activity to compute total_users in 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.csv before checking len(users_on_page) >= 2: Drops guest viewers missing from users.csv, making a 2-person shared document look like a 1-person solo document.
  • Using LIMIT 1 in 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.00 beats 900 / 1,000 = 0.90 even though 900 / 1,000 is 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 scores 1/1 at 0.207 while scoring 90/100 at 0.826) while still displaying raw collaboration_rate and total_users alongside 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_pairs to itself on page_id) emits m * (m - 1) pairs for a page of m viewers, so one 10,000-viewer all-hands page explodes into ~10^8 pairs while adding almost zero real 1-on-1 collaboration signal! First, cap or down-weight mega-pages (for instance, ignore pages with m > 200 viewers, or weight each shared page by 1 / (m - 1) so a 2-person page contributes 1.0 while a 101-person page contributes 0.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) and bookmark = 20% (1/5), whereas last-touch attribution (crediting the most recent view of (doc-10, ben) at minute 9) flips (doc-10, ben) from slack_share to bookmark, tying bookmark at 40%! 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

Similar questions

More Notion interview questions

All 9 Notion questions →