All practice tasks

Coding (Algo)

Detect a Connection Cycle

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

false

Example 2

{
  "directed": false,
  "edges": [
    [
      0,
      1
    ],
    [
      0,
      1
    ]
  ],
  "n": 2
}

Returns

true

Required complexity

O(n + m × α(n)) time and O(n + m) space, or O(n + m) with DFS and explicit edge identities

What this task practices

Detect a Connection Cycle is a coding (algo) interview exercise that trains prompt interpretation, explicit assumptions, a concrete response, and a clear explanation of tradeoffs. The catalog marks it as medium difficulty. It focuses on Technical Reasoning, Testing, Validation. The signed-in workspace provides the tools for the round and evaluates the attempt against task-specific criteria. Reference solutions, hidden checks, evaluator instructions, and candidate work remain private.

Sign in to startThe workspace and evaluation open after sign in.