Quick Overview

Given a mapping from group IDs to member elements, where an element can belong to several groups, answer whether pairs of elements are connected through chains of shared groups. It tests building a graph from group memberships, connected components, and handling many connectivity queries efficiently.

Check whether two elements are connected through shared groups

Company: Pinterest

Role: Machine Learning Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Technical Screen

You are given a mapping from group IDs to the elements each group contains. An element can belong to several groups. Two elements are directly related if some group contains both of them, and two elements are connected if a chain of directly related elements links them: for example, `a` and `c` are connected when `a` shares a group with `b` and `b` shares a group with `c`. In the interview this was a class that receives the group mapping once and then answers "are these two elements connected?" queries. Here, implement it as one function that receives the mapping and a batch of queries and answers each query. ### Function Signature ```python def are_connected(groups: dict[str, list[str]], queries: list[list[str]]) -> list[bool]: ``` ### Rules - Each query is a pair `[x, y]` of two different element names. Its answer is `True` if `x` and `y` are connected, directly or through any chain of shared groups, and `False` otherwise. - An element that appears in no group is connected to no other element, so any query that names it answers `False`. - An element whose every group contains only that element is connected to no other element. - Return one answer per query, in the same order as `queries`. ### Constraints - `0 <= len(groups) <= 10^4`; group IDs are distinct. - Each group lists between `0` and `10^4` distinct elements, and the total number of listed elements across all groups is at most `2 * 10^5`. - `1 <= len(queries) <= 10^5`; each query has exactly two elements `x` and `y`, with `x != y`. - Group IDs and element names are non-empty strings of at most 20 characters, each a lowercase English letter or a digit. Query elements need not appear in any group. ### Examples **Example 1** ```text Input: groups = {"g1": ["a", "b", "c"], "g2": ["c", "d"], "g3": ["e", "f"], "g4": ["g"]} queries = [["a", "d"], ["a", "e"], ["e", "f"], ["g", "a"], ["a", "z"]] Output: [True, False, True, False, False] ``` `a` and `d` are connected through `c`, which shares `g1` with `a` and `g2` with `d`. `e` and `f` share `g3` but nothing links them to `a`. `g` is the only member of `g4`. `z` appears in no group. **Example 2** ```text Input: groups = {"x": ["p", "q"], "y": ["q", "r"], "z": ["r", "s"], "w": []} queries = [["s", "p"], ["q", "s"]] Output: [True, True] ``` `s` shares `z` with `r`, `r` shares `y` with `q`, and `q` shares `x` with `p`. The empty group `w` changes nothing. **Example 3** ```text Input: groups = {} queries = [["a", "b"]] Output: [False] ``` With no groups, no two elements are connected.

Overview: Given a mapping from group IDs to member elements, where an element can belong to several groups, answer whether pairs of elements are connected through chains of shared groups. It tests building a graph from group memberships, connected components, and handling many connectivity queries efficiently.

Read the full Pinterest Machine Learning Engineer interview experience this question came from

You are given a mapping `groups` from group IDs to the elements each group contains. An element can belong to several groups. Two elements are **directly related** if some group contains both of them, and two elements are **connected** if a chain of directly related elements links them: for example, `a` and `c` are connected when `a` shares a group with `b` and `b` shares a group with `c`. In the interview this was a class that receives the group mapping once and then answers "are these two elements connected?" queries. Here, implement it as one function `are_connected(groups, queries)` that receives the mapping and a batch of queries and answers each query. ### Rules - Each query is a pair `[x, y]` of two different element names. Its answer is `True` if `x` and `y` are connected, directly or through any chain of shared groups, and `False` otherwise. - An element that appears in no group is connected to no other element, so any query that names it answers `False`. Only the names listed inside the groups are members; a string used as a group ID but never listed inside any group is a name that appears in no group. - An element whose every group contains only that element is connected to no other element. - Return one answer per query, in the same order as `queries`, as a list of booleans. All names are strings, including names made only of digits (`"01"` and `"1"` are different names). No numeric value is computed, so nothing approaches 2^31 - 1. ### Constraints - `0 <= len(groups) <= 10^4`; group IDs are distinct. - Each group lists between `0` and `10^4` distinct elements, and the total number of listed elements across all groups is at most `2 * 10^5`. - `1 <= len(queries) <= 10^5`; each query has exactly two elements `x` and `y`, with `x != y`. - Group IDs and element names are non-empty strings of at most 20 characters, each a lowercase English letter or a digit. Query elements need not appear in any group. ### Example 1 ```text Input: groups = {"g1": ["a", "b", "c"], "g2": ["c", "d"], "g3": ["e", "f"], "g4": ["g"]} queries = [["a", "d"], ["a", "e"], ["e", "f"], ["g", "a"], ["a", "z"]] Output: [True, False, True, False, False] ``` `a` and `d` are connected through `c`, which shares `g1` with `a` and `g2` with `d`. `e` and `f` share `g3`, but nothing links them to `a`. `g` is the only member of `g4`. `z` appears in no group. ### Example 2 ```text Input: groups = {"x": ["p", "q"], "y": ["q", "r"], "z": ["r", "s"], "w": []} queries = [["s", "p"], ["q", "s"]] Output: [True, True] ``` `s` shares `z` with `r`, `r` shares `y` with `q`, and `q` shares `x` with `p`. The empty group `w` changes nothing.

Constraints

  • 0 <= len(groups) <= 10^4; group IDs are distinct.
  • Each group lists between 0 and 10^4 distinct elements, and the total number of listed elements across all groups is at most 2 * 10^5.
  • 1 <= len(queries) <= 10^5; each query has exactly two elements x and y, with x != y.
  • Group IDs and element names are non-empty strings of at most 20 characters, each a lowercase English letter or a digit. Query elements need not appear in any group.

Examples

Input: ({'g1': ['a', 'b', 'c'], 'g2': ['c', 'd'], 'g3': ['e', 'f'], 'g4': ['g']}, [['a', 'd'], ['a', 'e'], ['e', 'f'], ['g', 'a'], ['a', 'z']])

Expected Output: [True, False, True, False, False]

Explanation: Source Example 1: a-d linked through c across g1 and g2; e-f share g3 only; g is alone in g4; z is in no group (mixed answers).

Input: ({'x': ['p', 'q'], 'y': ['q', 'r'], 'z': ['r', 's'], 'w': []}, [['s', 'p'], ['q', 's']])

Expected Output: [True, True]

Explanation: Source Example 2: chain s-r-q-p through groups z, y, x; the empty group w changes nothing.

Hints

  1. Being connected is symmetric and transitive: if x is connected to y and y to z, then x is connected to z. Think about what that means for sorting the elements into sets before you look at any query.
  2. Every member of a group is directly related to every other member of that group, but you do not have to record every pair to capture that.
  3. Decide what to answer when a query names something never listed inside any group, including a string that is only used as a group ID.

Connected Elements Through Shared Groups

mediumPinterestMachine Learning Engineer

You are given a mapping groups from group IDs to the elements each group contains. An element can belong to several groups. Two elements are directly related if some group contains both of them, and two elements are connected if a chain of directly related elements links them: for example, a and c are connected when a shares a group with b and b shares a group with c.

In the interview this was a class that receives the group mapping once and then answers "are these two elements connected?" queries. Here, implement it as one function are_connected(groups, queries) that receives the mapping and a batch of queries and answers each query.

Rules

  • Each query is a pair [x, y] of two different element names. Its answer is True if x and y are connected, directly or through any chain of shared groups, and False otherwise.
  • An element that appears in no group is connected to no other element, so any query that names it answers False. Only the names listed inside the groups are members; a string used as a group ID but never listed inside any group is a name that appears in no group.
  • An element whose every group contains only that element is connected to no other element.
  • Return one answer per query, in the same order as queries, as a list of booleans.

All names are strings, including names made only of digits ("01" and "1" are different names). No numeric value is computed, so nothing approaches 2^31 - 1.

Constraints

  • 0 <= len(groups) <= 10^4; group IDs are distinct.
  • Each group lists between 0 and 10^4 distinct elements, and the total number of listed elements across all groups is at most 2 * 10^5.
  • 1 <= len(queries) <= 10^5; each query has exactly two elements x and y, with x != y.
  • Group IDs and element names are non-empty strings of at most 20 characters, each a lowercase English letter or a digit. Query elements need not appear in any group.

Example 1

Input:  groups  = {"g1": ["a", "b", "c"], "g2": ["c", "d"], "g3": ["e", "f"], "g4": ["g"]}
        queries = [["a", "d"], ["a", "e"], ["e", "f"], ["g", "a"], ["a", "z"]]
Output: [True, False, True, False, False]

a and d are connected through c, which shares g1 with a and g2 with d. e and f share g3, but nothing links them to a. g is the only member of g4. z appears in no group.

Example 2

Input:  groups  = {"x": ["p", "q"], "y": ["q", "r"], "z": ["r", "s"], "w": []}
        queries = [["s", "p"], ["q", "s"]]
Output: [True, True]

s shares z with r, r shares y with q, and q shares x with p. The empty group w changes nothing.

Examples

Example 1
Input
({'g1': ['a', 'b', 'c'], 'g2': ['c', 'd'], 'g3': ['e', 'f'], 'g4': ['g']}, [['a', 'd'], ['a', 'e'], ['e', 'f'], ['g', 'a'], ['a', 'z']])
Output
[True, False, True, False, False]
Notes
Source Example 1: a-d linked through c across g1 and g2; e-f share g3 only; g is alone in g4; z is in no group (mixed answers).
Example 2
Input
({'x': ['p', 'q'], 'y': ['q', 'r'], 'z': ['r', 's'], 'w': []}, [['s', 'p'], ['q', 's']])
Output
[True, True]
Notes
Source Example 2: chain s-r-q-p through groups z, y, x; the empty group w changes nothing.

Constraints

  • •0 <= len(groups) <= 10^4; group IDs are distinct.
  • •Each group lists between 0 and 10^4 distinct elements, and the total number of listed elements across all groups is at most 2 * 10^5.
  • •1 <= len(queries) <= 10^5; each query has exactly two elements x and y, with x != y.
  • •Group IDs and element names are non-empty strings of at most 20 characters, each a lowercase English letter or a digit. Query elements need not appear in any group.

Comments (0)

No comments yet. Be the first to comment!

Submit your answer

Approved first answer today earns 30 XP
Bold⌘BItalic⌘IInline code⌘`Bullet listTab to nest (○ ■)Numbered listTab to nest (a. i.)QuoteCode block
Formatting help
Signature
def are_connected(groups: dict[str, list[str]], queries: list[list[str]]) -> list[bool]:
Sample call
are_connected({'g1': ['a', 'b', 'c'], 'g2': ['c', 'd'], 'g3': ['e', 'f'], 'g4': ['g']}, [['a', 'd'], ['a', 'e'], ['e', 'f'], ['g', 'a'], ['a', 'z']])
Language
Case 1
Input
({'g1': ['a', 'b', 'c'], 'g2': ['c', 'd'], 'g3': ['e', 'f'], 'g4': ['g']}, [['a', 'd'], ['a', 'e'], ['e', 'f'], ['g', 'a'], ['a', 'z']])
Expected
[True, False, True, False, False]
Case 2
Input
({'x': ['p', 'q'], 'y': ['q', 'r'], 'z': ['r', 's'], 'w': []}, [['s', 'p'], ['q', 's']])
Expected
[True, True]

Browse More Questions

Show the approach

Approach

Connectivity is the transitive closure of "shares a group", so it is an equivalence relation: every listed element belongs to exactly one connected set, and a query only asks whether its two names lie in the same set.

Algorithm: give each distinct listed element an integer index the first time it is seen, and keep a disjoint-set union (union-find) over those indices with path compression and union by size. For each group, union every member with the group's first member. That takes len(group) - 1 unions instead of one per pair, and it still puts the whole group in one set. Group IDs never become nodes. After all groups are processed, answer each query: if either name was never listed in any group the answer is False; otherwise the answer is whether both names have the same root.

Invariant: after processing any prefix of the groups, two elements share a root exactly when they are connected using only the groups processed so far. Unioning each member with the first member keeps this true because the members of one group are pairwise directly related. Merging whole sets means a later group that bridges two earlier components joins every element of both, not only the elements it names, which is what a chain such as x0-x1-...-x50 needs.

Edge cases: an empty mapping or empty groups create no nodes, so every query is False; an element whose groups are all singletons stays alone in its set, and since x != y no other element shares its root; a group ID equal to an element name has no effect because IDs are never nodes; names are compared as strings, so "01" and "1" stay distinct; the same pair asked twice or in reverse gets the same answer because set membership is symmetric.

Time complexity:
O((T + Q) * α(T)) expected, where T is the total number of listed elements and Q is the number of queries
Space complexity:
O(T + Q)