KatInterview

Filter Users by Active Connection Threshold

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphsgraphshash-tablesimulation

Last 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_a and user_b are user identifiers (strings or integers)
    • action is 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 user a.

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.