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

  1. access_rows: each dictionary records one page-open event and contains:
    • page_id (str or int): document identifier.
    • user_id (str or int): user who opened the page.
    • event_ts (str): UTC timestamp string comparable in chronological order.
    • is_creator (bool): True for the page author; False for a non-author collaborator.
    • collab_source (Optional[str]): acquisition channel for collaborator visits (is_creator == False); None for author visits. Treat None or "" on a collaborator row as "unknown".
  2. user_rows: each dictionary maps a registered account to its country via user_id (str or int) and country (str). If user_rows repeats a user_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

  1. "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 earliest event_ts (preserving first appearance in access_rows if 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 a 0 to 100 scale)
    • Return [] if zero collaborator memberships exist.
  2. "q2" — Top co-collaborator for target_user_id (Dict):
    • Treat every distinct (page_id, user_id) pair (authors and non-authors alike) as a member of page_id. Two distinct users co-collaborate on page_id whenever both belong to that page's member set.
    • Select the user other_id != target_user_id who shares the largest count of distinct pages with target_user_id, breaking ties by the smallest user_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 with target_user_id, return None for "top_collaborator_user_id" and 0 for "num_shared_pages".
  3. "q3" — Highest-rate country (Optional[Dict]):
    • A user counts as having collaborated if they belong to at least one page_id that has 2 or more distinct accessing users overall (including users absent from user_rows).
    • Across each country present in user_rows, define:
      • "num_users_in_country": total distinct registered users in that country from user_rows (including accounts with zero activity in access_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 (a float in [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 smallest country string. Return None when user_rows is empty.

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_id values within a single call share a mutually comparable type (str or int), and page_id values are hashable (str or int).
  • event_ts strings within a call follow a uniform lexicographically sortable UTC format.

Step-by-step walkthrough

  1. Understand the tables and metric rules

    We receive two parsed tables (access_rows and user_rows) along with target_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 with is_creator = False — grouped by collab_source. Report pct_of_collaborators on a 0..100 percentage scale, ordered ascending by collab_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 with target_user_id, breaking ties by the smallest user_id. When nobody shares a page with the target, return top_collaborator_user_id = None and num_shared_pages = 0. - Q3 (q3): Across every country in user_rows: - Denominator (num_users_in_country): all distinct accounts registered in that country in user_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 >= 2 distinct users overall. - Rate (collaboration_rate): numerator / denominator on a 0..1 proportion scale, breaking ties alphabetically by country (or None when user_rows is empty).

  2. Build a page-to-users lookup once

    Both Q2 and Q3 ask which distinct users belong to each document. One pass over access_rows builds pages (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 pages
    
  3. Q1: 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' at 09:15 and 'shared_url' at 14:00? Retaining the row with the earliest event_ts records 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, and row["collab_source"] or "unknown" buckets missing channels cleanly.

    When access_rows contains zero collaborator visits, counts_by_source is 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 distribution
    
  4. Q2: count shared pages with the target user

    Rather than comparing target_user_id against every user in the directory, inspect each page's member set in pages: - Skip any page where target_user_id not in page_members in O(1) average time. - On every page containing target_user_id, add 1 to shared_counts[other_user] for each other_user != target_user_id.

    Because page_members is already a set, 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,
        }
    
  5. 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. - When len(page_members) >= 2, every member of page_members shared that document with at least one other distinct person!

    One linear scan over pages populates collaborated_users with zero O(k^2) pair blowup on widely read documents.

    Next, map user_rows into country_by_user and tally total_in_country and collab_in_country. Accounts appearing only in access_rows without a user_rows record still help make len(page_members) >= 2 while being omitted from country totals.

    To compare rates collab_count / total_count vs best_collab / best_total without floating-point rounding drift (such as 1/3 vs 2/6), cross-multiply collab_count * best_total against best_collab * total_count using 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,
        }
    
  6. Trace Example 1 end to end

    Walk through analyze_document_collaboration on 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),
        }
    
  7. 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 the R events once with O(1) average hash-set insertion, storing M unique (page, user) memberships across page sets.
  • Q1 (source_distribution) — O(R + C log C) time, O(M) space: scans R events once to record earliest channels for up to M collaborator memberships, aggregates counts in O(M) time, and sorts C channel strings in O(C log C) time.
  • Q2 (top_collaborator) — O(M) worst-case time, O(U) space: tests target_user_id in page_members in O(1) time across P pages and iterates over members only on pages containing the target (at most M total entries).
  • Q3 (top_country) — O(M + U) time, O(M + U) space: scans page sets (O(M) total items) to mark collaborating accounts, scans U directory rows to compute per-country totals, and picks the maximum in one pass over countries.
  • Overall — O(R + U + C log C) time and O(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_source across visits: Q1 attributes the membership to its earliest event_ts (breaking timestamp ties by log order via strict <).
  • None or empty collab_source on a collaborator event: grouped under "unknown" so percentages sum to 100%.
  • 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 = None and num_shared_pages = 0.
  • Inactive accounts in user_rows: accounts with zero visits (such as 60, 70, 80 in Example 2) still count in their country's denominator num_users_in_country.
  • Visiting accounts absent from user_rows: still count in Q1, Q2, and toward making len(page_members) >= 2 in Q3, while having no country bucket in Q3.
  • Empty user_rows: Q3 returns None.
  • Loading raw CSV strings in production: csv.DictReader yields "FALSE" as a non-empty truthy str, so normalize row["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_id to match itself in Q2: omitting other_user != target_user_id makes 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_rows and computes a different ratio.
  • Confusing 0..100 vs 0..1 scales: Q1 reports percentages on 0..100 (33.333...), whereas Q3 reports proportions on 0..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 100 registered 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) where m (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 a 1/1 country cannot beat a 999/1000 country.
  • 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 between target_user_id and other_user, define their shared-activity timestamp on that document — such as min(latest_visit[page, target], latest_visit[page, other]) (the earliest point by which both had visited) or max(...) (most recent visit by either member) — and maintain last_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 (computing MIN_BY(collab_source, event_ts) on non-author rows), which typically shrinks raw event volume by 10x–100x. From that compact membership table, Q1 and Q3 (COUNT per page followed by a hash/broadcast join to users) finish in linear O(M + U) distributed scans. Computing Q2 for all users at once is the only quadratic risk because a 10,000-viewer company-wide page produces ~10^8 pairs in a self-join; in practice, filter out giant broadcast documents (e.g., > 500 viewers) since viewing an all-hands announcement does not represent 1-on-1 collaboration.

Follow-up questions

Similar questions

More Notion interview questions

All 9 Notion questions →