Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

Does an undirected graph contain a cycle?

Easy · Target 12 minutes · Graphs

A graph has n nodes numbered 0 to n − 1 and a list of undirected edges. No edge joins a node to itself and no edge is repeated. Return true if the graph contains a cycle, and false otherwise. The graph need not be connected.

Examples

InputOutputWhy
n = 6, edges = [[0,1],[1,2],[0,3],[3,4],[4,1],[2,5]]true0–1–4–3–0 is a cycle.
n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]falseA path.
n = 6, edges = [[0,1],[2,3],[3,4],[4,2]]trueThe cycle is in the second piece; the first piece has none.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 0 ≤ edges.length ≤ 10⁵
  • No self-loops and no repeated edges

Hints

Hint 1

Search from every unvisited node, because the cycle may be in any piece of the graph.

Hint 2

Remember, for each node, the node you reached it from.

Hint 3

From u, a neighbour that is already visited and is not the node you came from means a cycle.

Where people lose marks

  • Treating the parent as a cycle: every undirected edge is seen from both ends.
  • Searching only from node 0, which misses a cycle in another piece of the graph.
  • Using the directed-graph colours here. They work, but the parent check is all an undirected graph needs.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.