Service Inventory Filter and Dependency Risk Report
Trees & GraphsAuto-graded · 14 test casesLast updated
Filter a service inventory by namespace, attributes and status, then compute transitive dependencies and risk flags from a root service, handling cycles and dangling references.
You are given a list of service records describing a deployment. Each record is a dictionary with these keys:
id: a unique string such as"namespace/name"name: a stringnamespace: a stringattributes: a dictionary mapping string keys to string valuesstatus: one of"Healthy","Degraded","Down","Unknown"dependencies: a list of service IDs that this service depends on
Write a single function that takes the list of services, a criteria dictionary, and a root_id string, and returns a dictionary with three keys: filtered, dependency_chain, and status_chain.
Part 1: filtered
criteria may contain any of the following optional keys:
namespace: if present (and notNone), a service must have exactly this namespace.attributes: a dictionary of required key/value pairs. A service matches only if every pair appears in its ownattributes. A missing key counts as a mismatch. If this key is omitted or empty, there is no attribute constraint.statuses: a list of allowed statuses. If this key is omitted orNone, any status is allowed. If it is an empty list, no service matches.
A service must satisfy all of the given criteria. filtered contains the full original service records that match, sorted ascending by id. An empty criteria matches every service.
Part 2: dependency_chain
Find every service that is transitively reachable from root_id by following dependencies. The root itself is not included unless it can be reached again through a cycle. Rules:
- Dependency IDs that do not exist in the inventory are ignored; they never appear in the output and never cause an error.
- Cycles (including self-dependencies) must not cause infinite loops.
- Each reachable service appears exactly once, even if reachable by multiple paths or listed multiple times.
- If
root_idis not in the inventory, the result is an empty list.
dependency_chain is a list of dictionaries {"id": ..., "status": ...}, sorted ascending by id.
Part 3: status_chain
Report the status of the root and every service reachable from it. Each entry is a dictionary:
{"id": ..., "status": ..., "may_affect_root": ...}
- The set of services is every service in
dependency_chain, plus the root itself (if it exists in the inventory). Each service appears once. may_affect_rootisTrueif the service is not the root and its status is"Degraded"or"Down"; otherwiseFalse. The root is never flagged.- Entries are sorted ascending by
id. - If
root_idis not in the inventory, the result is an empty list.
Constraints
- Sorting by
idis ordinary string comparison. - Service IDs are unique.
- Records may omit
attributesordependencies; treat a missing one as empty. - Do not mutate the input.
- The dependency graph can be deep, so avoid relying on deep recursion.
Examples
Example 1
Input: analyze_services([{'id': 'app/web', 'name': 'web', 'namespace': 'app', 'attributes': {'tier': 'frontend'}, 'status': 'Healthy', 'dependencies': ['app/cache', 'app/db']}, {'id': 'app/cache', 'name': 'cache', 'namespace': 'app', 'attributes': {'tier': 'data'}, 'status': 'Degraded', 'dependencies': ['app/db']}, {'id': 'app/db', 'name': 'db', 'namespace': 'app', 'attributes': {'tier': 'data'}, 'status': 'Healthy', 'dependencies': []}], {'namespace': 'app', 'attributes': {'tier': 'data'}, 'statuses': ['Healthy', 'Degraded']}, 'app/web')
Output: {'filtered': [{'id': 'app/cache', 'name': 'cache', 'namespace': 'app', 'attributes': {'tier': 'data'}, 'status': 'Degraded', 'dependencies': ['app/db']}, {'id': 'app/db', 'name': 'db', 'namespace': 'app', 'attributes': {'tier': 'data'}, 'status': 'Healthy', 'dependencies': []}], 'dependency_chain': [{'id': 'app/cache', 'status': 'Degraded'}, {'id': 'app/db', 'status': 'Healthy'}], 'status_chain': [{'id': 'app/cache', 'status': 'Degraded', 'may_affect_root': True}, {'id': 'app/db', 'status': 'Healthy', 'may_affect_root': False}, {'id': 'app/web', 'status': 'Healthy', 'may_affect_root': False}]}
Example 2
Input: analyze_services([], {}, 'missing')
Output: {'filtered': [], 'dependency_chain': [], 'status_chain': []}
Hints
Hint 1
Build a dictionary from id to service once, so lookups and detection of missing dependency IDs are O(1).
Hint 2
Treat the three outputs as independent computations: a filter with all conditions combined, then one graph reachability search whose result feeds both chain outputs.
Hint 3
Use an iterative DFS or BFS with a visited set; seed it with the root's direct dependencies (not the root itself) and skip IDs that are already visited or not in the inventory.
Hint 4
Distinguish statuses being None (no restriction) from an empty list (nothing allowed), and make sure the root is added to the status report separately without ever being flagged.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The function does three jobs over the same inventory, so first build one index from id to service record. That gives constant-time lookups and makes it trivial to detect dependency IDs that do not exist.
Filtering. A service is kept only if all three checks pass:
- the namespace criterion is absent or equals the service's namespace,
- every required attribute pair is present with the same value (a missing key is a mismatch, and an empty requirement is trivially satisfied),
- the status criterion is absent (
None) or contains the service's status.
The check on statuses uses is None rather than truthiness, because an empty list must mean "nothing is allowed". The kept records are sorted by id.
Dependency chain. This is plain reachability. Run an iterative DFS starting from the root's direct dependencies. A visited set serves as both cycle protection and the final result. Any ID that is already visited or not in the inventory is skipped. The root is not pre-seeded, so it appears only if a cycle leads back to it, which is correct because it then really is its own transitive dependency. The result is sorted by id.
Status chain. Reporting "every path" explicitly would be exponential on diamond-shaped graphs and unbounded with cycles. The question of whether a bad dependency can affect the root is answered exactly by reachability: a service can affect the root if and only if some path from the root reaches it. So we report each reachable service once, plus the root itself, and flag may_affect_root when the service is not the root and is Degraded or Down.
Why it is correct
- Each filter condition is evaluated independently and combined with logical AND, so omitted criteria impose no restriction.
- Each reachable node is added to the visited set at most once, so every edge is processed a bounded number of times and the loop terminates even with cycles. Every existing node with a path of existing nodes from the root is eventually popped and recorded.
- Skipping unknown IDs means dangling references never surface or fail.
- Using sets for the status IDs means the root appears once even if a cycle makes it reachable, and the
service_id != root_idcheck ensures it is never flagged. - The traversal is iterative, so deep dependency chains cannot overflow the recursion limit.
Complexity
Let N be the number of services, E the number of dependency edges, A the number of required attributes, and R the number of reachable services.
- Index: O(N) time and space.
- Filter: O(N·A + N log N) time, O(N) space.
- Traversal: O(N + E) time and space.
- Output sorting: O(R log R).
Reference solution
from typing import Dict, List
def analyze_services(services: List[Dict], criteria: Dict, root_id: str) -> Dict:
by_id = {service["id"]: service for service in services}
namespace = criteria.get("namespace")
required_attributes = criteria.get("attributes", {})
allowed_statuses = criteria.get("statuses")
filtered = [
service
for service in services
if (namespace is None or service["namespace"] == namespace)
and all(
service.get("attributes", {}).get(key) == value
for key, value in required_attributes.items()
)
and (
allowed_statuses is None
or service["status"] in allowed_statuses
)
]
filtered.sort(key=lambda service: service["id"])
reachable = set()
stack = (
list(reversed(by_id[root_id].get("dependencies", [])))
if root_id in by_id
else []
)
while stack:
service_id = stack.pop()
if service_id in reachable or service_id not in by_id:
continue
reachable.add(service_id)
stack.extend(reversed(by_id[service_id].get("dependencies", [])))
dependency_chain = [
{"id": service_id, "status": by_id[service_id]["status"]}
for service_id in sorted(reachable)
]
status_ids = set(reachable)
if root_id in by_id:
status_ids.add(root_id)
status_chain = [
{
"id": service_id,
"status": by_id[service_id]["status"],
"may_affect_root": (
service_id != root_id
and by_id[service_id]["status"] in {"Degraded", "Down"}
),
}
for service_id in sorted(status_ids)
]
return {
"filtered": filtered,
"dependency_chain": dependency_chain,
"status_chain": status_chain,
}