You are given a directed dependency graph representing services in a system.
-
There are
n
services, labeled from
0
to
n - 1
.
-
You are given a list of directed edges
dependencies
, where each element is a pair
[a, b]
meaning
service a depends on service b
(i.e., there is a directed edge
a -> b
).
Assume:
-
1 <= n <= 10^5
-
0 <= a, b < n
-
There may be zero or more edges.
Task:
-
Implement a function that determines whether there is at least one cycle in this directed graph.
-
Return
true
if there is a cycle.
-
Return
false
otherwise.
-
Follow-up: Now you are given
multiple dependency arrays
instead of just one. Each array represents an additional list of edges on the same set of services. For example:
-
dependencies1
,
dependencies2
, ...,
dependenciesk
Each
dependenciesi
is a list of
[a, b]
pairs as defined above. Treat the union of all these edges as a single directed graph and determine whether this combined graph contains any cycle.
Describe the approach, data structures, and algorithm you would use, and analyze the time and space complexity.