Filter Users by Active Connection Threshold
Trees & GraphsAuto-graded · 18 test casesLast updated
Tests graph maintenance with dynamic edge insertion and deletion, proper handling of duplicates and missing edges, and final degree counting.
You are given a sequence of relationship operations and a threshold value. Each operation modifies an undirected graph of user connections.
Write a function that processes the operations in order to build the final state of the graph, then returns how many users have a degree (number of connections) strictly exceeding the threshold.
Input
operations: A list of operations, where each operation is a list[user_a, user_b, action]user_aanduser_bare user identifiers (strings or integers)actionis either"connect"or"disconnect"
threshold: An integer
Output
Return the count of users whose final degree is strictly greater than threshold.
Behavior
- Connections are undirected: a connection between A and B means both A is connected to B and B is connected to A.
- A connection either exists or does not exist. Applying
"connect"multiple times for the same pair has no additional effect. - Applying
"disconnect"to a pair that is not currently connected has no effect (it is not an error). - Users are registered when they first appear in any operation, even if that operation is a
"disconnect". - Self-connections
[a, a, "connect"]are allowed and count as degree 1 for usera.
Constraints
0 ≤ len(operations) ≤ 100,000-1000 ≤ threshold ≤ 1000- User identifiers are hashable (strings or integers)
- The comparison is strictly greater than (
>), not greater than or equal to
Examples
Example 1
Input: filter_users_by_connections([[1, 2, 'connect'], [2, 3, 'connect'], [1, 3, 'connect'], [2, 3, 'disconnect']], 1)
Output: 1
Example 2
Input: filter_users_by_connections([['a', 'b', 'connect'], ['a', 'c', 'connect'], ['d', 'a', 'connect']], 2)
Output: 1
Hints
Hint 1
Use a dictionary mapping each user to the set of their current neighbors to handle duplicate operations naturally.
Hint 2
The set data structure's add and discard methods are idempotent and safe, making edge updates straightforward.
Hint 3
Count the final degrees by iterating over the neighbor sets after all operations are processed.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is maintaining an undirected graph that evolves through connection and disconnection operations, then querying the final degree distribution.
The key insight is to represent the graph as a dictionary mapping each user to a set of their current neighbors. Sets provide exactly the semantics we need:
- Idempotent additions: Adding a neighbor that already exists in the set has no effect, naturally handling duplicate
"connect"operations - Safe removals: The
discardmethod removes an element if present, or does nothing otherwise, perfectly handling"disconnect"on non-existent edges
For each operation, we ensure both users exist in the dictionary (lazy registration), then update their neighbor sets based on the action. Since connections are undirected, we update both directions symmetrically.
After processing all operations, each user's degree is simply the size of their neighbor set. We count how many of these sizes exceed the threshold.
Why This Works
The algorithm maintains the invariant that after each operation, user_b in neighbors[user_a] if and only if the edge exists and the graph is symmetric. Initial state satisfies this (no users, no edges). Each "connect" establishes the edge in both directions; each "disconnect" removes it from both directions. The invariant is preserved throughout.
Complexity
Time: O(E), where E is the number of operations. Each operation performs constant-time hash table lookups and set operations. The final counting pass visits each user once, which is at most 2E users.
Space: O(U + D), where U is the number of distinct users and D is the total degree (sum of all final degrees). Each edge is stored twice (once per endpoint).
Implementation
from typing import List
def filter_users_by_connections(operations: List[List], threshold: int) -> int:
neighbors = {}
for user_a, user_b, action in operations:
if user_a not in neighbors:
neighbors[user_a] = set()
if user_b not in neighbors:
neighbors[user_b] = set()
if action == "connect":
neighbors[user_a].add(user_b)
neighbors[user_b].add(user_a)
elif action == "disconnect":
neighbors[user_a].discard(user_b)
neighbors[user_b].discard(user_a)
return sum(len(neighbor_set) > threshold for neighbor_set in neighbors.values())