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