Cycle detection · Medium
A graph validator checks whether a connection set contains a cycle. The input explicitly states whether links are directed. This matters because one undirected link does not form a cycle merely because it can be traversed in both directions.
Return whether any component contains a cycle under the declared directed or undirected multigraph rules.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ n: integer, edges: [integer, integer][], directed: boolean }
Fields
- n is the node count; directed selects directed versus undirected semantics. edges contains [from,to] pairs.
- For directed=false each array entry is one undirected edge; do not supply a mirrored entry unless it is a second distinct edge.
Output
Return value
- Return a boolean. A self-loop is a cycle. Two parallel undirected edges form a two-edge cycle; one undirected edge does not.
- For directed graphs, a cycle must follow edge direction. Check disconnected components too. Empty graphs are acyclic.
Constraints
- 0 <= n <= 100000; 0 <= edges.length <= 200000; every endpoint is a valid node label.
- source and target, when used, are either -1 or valid node labels. Empty graphs use -1.
Examples
Example 1
{
"directed": false,
"edges": [
[
0,
1
]
],
"n": 2
}Returns
falseExample 2
{
"directed": false,
"edges": [
[
0,
1
],
[
0,
1
]
],
"n": 2
}Returns
trueRequired complexity
O(n + m × α(n)) time and O(n + m) space, or O(n + m) with DFS and explicit edge identities