Quick revision
The short answer
Detecting a cycle in an undirected graph is a graph traversal problem. We run a BFS from every vertex not yet visited and remember the edge that first reached each vertex; finding an already visited vertex along any other edge means there are two routes to it, which is a cycle. It takes O(V + E) time and space.
The solution
What it costs
| Approach | Time | Extra space |
|---|---|---|
| Close each road and search again | O(E * (V + E)) or worse | O(V) |
| One BFS per piece, skip the road we came by | O(V + E) | O(V + E) |
| Union-find over the edge list | nearly O(E) | O(V) |
What to remember
We detected a cycle in an undirected graph with one BFS per piece of the graph. Each vertex remembers the edge it was first reached by, so the road back to where we came from is skipped, and any other edge that reaches a visited vertex is a second route and closes a loop. That takes O(V + E) time and space. The clue to remember is a question about connections in a graph: walk it once, and remember that the edges a traversal uses form a tree, so any edge left over makes a cycle.
1What it means for a map of roads to have a loop
Think of a few towns joined by two-way roads. If you can leave your town by one road and come back home by a different road, without using any road twice, the map has a loop. Some maps have none: between any two towns there is only one way to travel, like the branches of a tree, and the only way home is back along the road you took.
That is exactly our question. A graph is a set of points, called vertices, joined by lines, called edges. Our vertices are towns numbered 0 to n - 1, and each edge is a road, given as a pair such as {0, 1}. Undirected means every road is two-way. A cycle is a route that starts and ends at the same vertex, uses at least one edge, and never uses the same edge twice. We must return true if the graph has one.
Our example, used throughout, has 4 vertices and the edges 0-1, 1-2, 2-0 and 2-3. Vertices 0, 1 and 2 form a triangle, so the answer is true. For contrast, the edges 0-1, 1-2 and 1-3 make a graph shaped like a tree, a connected graph with no cycle, and the answer is false.
Graph questions can feel large, because a map may have thousands of roads. This one is smaller than it looks. One organised walk over the map, with one small note kept for each town, is enough, and every step can be traced on paper.
Each cell is a vertex. The panel lists, for each vertex, the vertices it shares an edge with, in the order the Java code stores them.
- 0 meets
- 1, 2
- 1 meets
- 0, 2
- 2 meets
- 1, 0, 3
- 3 meets
- 2
1The edges 0-1, 1-2 and 2-0 form a triangle, marked here, and 2-3 hangs off it. The triangle is the cycle we expect the search to find.
What to assume
- Is the graph connected, all in one piece?
- Not necessarily, so a loop may hide in any piece.
- Can there be a self-loop, a road from a town to itself, or two roads between the same pair?
- Both count as cycles.
- How large can it be?
- Around 100,000 vertices and edges, which rules out anything quadratic and makes deep recursion risky.
Let us do the example by hand first. From 0 take the road to 1, then the road from 1 to 2, then the road 2-0 back home. We used three different roads, so that is a loop. In the tree example, start at 1: each of the roads to 0, 2 and 3 ends at a town with no other road, so the only way back is the road we came by, which we may not reuse.
A careful candidate asks a few questions first. Is the graph connected, all in one piece? Not necessarily, so a loop may hide in any piece. Can there be a self-loop, a road from a town to itself, or two roads between the same pair? Both count as cycles. How large can it be? Around 100,000 vertices and edges, which rules out anything quadratic and makes deep recursion risky.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise a graph traversal problem
A beginner often starts by counting. A map with no loop has at most V - 1 roads for V towns, so 4 roads on 4 towns must contain a loop. That is a good instinct, but the count alone fails when the graph is in pieces: 5 towns with the roads 0-1, 2-3, 3-4 and 4-2 have only 4 roads, yet 2, 3 and 4 form a triangle. Others try to list every possible route, which explodes on a large map. We need something more organised.
Let us take the clues one at a time. The first is the pair of words graph and contains a cycle. The question is about how vertices are connected, and questions of connection, can I get from here to there, and by how many routes, are answered by walking the graph and seeing what we meet.
The second clue is the word undirected. Every road is two-way, so when we stand at either end we see the same road. That is a warning: when we walk to a new town, the road we just used will appear in that town's list too. Keep it in mind, because it is the trap of this problem.
Together the clues point to the graph traversal pattern. A traversal means visiting every vertex in an organised way, following edges and marking each vertex visited so none is handled twice. Breadth-first search, BFS, uses a queue, a line where the first in is the first out, and spreads outwards like ripples on a pond. Depth-first search, DFS, follows one path as far as it goes before backing up. The rule to carry to new problems: a traversal finds each new vertex along exactly one edge, those edges form a tree, and any other edge it meets closes a loop.
Some patterns look similar but do not fit as they are. Topological sorting and the three-colour DFS detect cycles in directed graphs, where roads are one-way and the rules differ. Union-find, a structure that tracks which vertices are already joined, is a real alternative here, and the FAQs show it.
3The brute force, closing one road at a time
The brute force rests on a plain fact. A road u-v lies on a loop exactly when u and v are still connected after that road is closed, because the other route plus the road closes the loop. So we close each road in turn and search from u to see whether v can still be reached. It is honest, correct, and easy to check.
Let us do it by hand. Close e0, the road 0-1. Can 0 still reach 1? From 0 the road 2-0 takes us to 2, and the road 1-2 takes us to 1, so yes, and we return true after the first test. On the tree example every test fails: with 0-1 closed, 0 has no roads at all; with 1-2 closed, 1 reaches 0 and 3 but not 2; and with 1-3 closed, 1 cannot reach 3. So the answer is false.
Now count. Each search may pop every vertex, and this version scans all E edges for each one, so one search can cost V times E steps, and we run up to E searches. Even with neighbour lists each search costs O(V + E), so the total is O(E * (V + E)). With 100,000 roads that is billions of steps. The space is O(V) for the seen array and the stack.
Where is the waste? Every search rediscovers the same towns along the same roads, and only the closed road changes. A single walk already looks along every road once. So we ask: can one walk decide, at the moment it looks along a road, whether that road closes a loop?
4Getting to one traversal, one observation at a time
Picture BFS as a message spreading from town 0. Each town that hears it passes it on along its roads, and each town remembers the road the message first arrived by. Every town except the start hears it first along exactly one road, so a map of V towns has V - 1 such first roads. Together they join every town without any loop, which makes them a tree, called the BFS tree.
Now look at a road that is not in the tree. It joins two towns that the tree already connects some other way, so tree route plus this road makes a loop. That gives the whole method. While we walk, whenever we look along a road and find a town that has already heard the message, we have found a second route to it, and there is a cycle.
Each picture shows the tree a full BFS from vertex 0 would build, with the start at the top. The panel lists the edges the tree did not use.
- tree edges
- 0-1, 1-2, 1-3
- left over
- none
- cycle
- no
1For the edges 0-1, 1-2 and 1-3, the BFS tree from 0 uses all three. Four vertices need three tree edges, nothing is left over, so there is no cycle.
- tree edges
- 0-1, 2-0, 2-3
- left over
- 1-2
- cycle
- yes, 0-1-2-0
2For our example the tree uses 0-1, 2-0 and 2-3. The edge 1-2 is left over, and it joins 1 and 2, already joined through 0, so 0-1-2-0 is a loop.
Here comes the question every beginner meets. Try the rule on the tree example. From 0 we visit 1. Then, standing at 1, we look along its roads, and the first one leads to 0, which has already heard the message. Does the tree have a cycle? No. That road is e0, the very road the message used to reach 1, seen from the other end. So the rule needs one exception: skip the road you arrived by.
Textbooks often skip the parent vertex, the town we came from, instead of the parent road. That is almost the same, but not quite. With two separate roads between 0 and 1, the map does have a loop of two roads, and skipping every road to the parent town would wrongly ignore the second one. So each entry in a town's list keeps the road's number as well as the neighbour, and an array called cameBy remembers, for each town, the number of the road it was reached by.
Why is this correct? Every road the search looks along, other than the road a town arrived by, either reaches a new town and becomes a tree road, or reaches a visited town and is reported. If the graph has a cycle, its roads cannot all be tree roads, because the tree has no loop, so some road must be reported. And a reported road always closes a loop, as we saw.
Two small details finish the design. An outer loop starts a fresh search from every vertex no earlier search reached, so a loop in a separate piece is still found. And we mark a vertex visited when we add it to the queue, not when we take it out, so no vertex is queued twice. The mistake beginners make most often is forgetting the parent road and reporting a cycle in every graph with at least one edge.
5Watching the search find the triangle
The picture runs the Java search on our example, one action per frame, with frames taken from a run of the code. Each cell is a vertex. Visited vertices are marked as done, the vertex taken from the queue is u, and the neighbour we are looking at is v. The panel shows the queue, the cameBy notes and the edge being examined.
Cells are vertices. u is the vertex taken from the queue and v the neighbour being examined.
- edges
- e0 0-1, e1 1-2, e2 2-0, e3 2-3
- queue
- empty
- cameBy
- nothing yet
1Before the search nothing is visited. The four edges are numbered e0 to e3, and each vertex will remember the edge it was reached by.
- edges
- e0 0-1, e1 1-2, e2 2-0, e3 2-3
- queue
- [0]
- cameBy
- 0: -1
2We start at vertex 0. It is marked visited and put in the queue, and it came by no edge, so
cameBy[0] is -1.- edges
- e0 0-1, e1 1-2, e2 2-0, e3 2-3
- queue
- []
- cameBy
- 0: -1
- 0 meets
- 1 by e0, 2 by e2
3We take 0 out of the queue and look along each of its edges in turn. Its list holds 1, by e0, and 2, by e2.
- edges
- e0 0-1, e1 1-2, e2 2-0, e3 2-3
- queue
- [1]
- cameBy
- 0: -1, 1: e0
- looking at
- e0 (0-1)
4Edge e0 leads to 1, which is not visited. We visit it, record that it came by e0, and add it to the queue.
- edges
- e0 0-1, e1 1-2, e2 2-0, e3 2-3
- queue
- [1, 2]
- cameBy
- 0: -1, 1: e0, 2: e2
- looking at
- e2 (2-0)
5Edge e2 leads to 2, also new. We visit it, record that it came by e2, and add it. Vertex 0 has no more edges.
- edges
- e0 0-1, e1 1-2, e2 2-0, e3 2-3
- queue
- [2]
- cameBy
- 0: -1, 1: e0, 2: e2
- 1 meets
- 0 by e0, 2 by e1
6We take 1 out of the queue. Its list holds 0, by e0, and 2, by e1. Remember that 1 itself came by e0.
- edges
- e0 0-1, e1 1-2, e2 2-0, e3 2-3
- queue
- [2]
- cameBy[1]
- e0
- looking at
- e0 (0-1), skip
7Edge e0 leads back to 0, which is visited, but e0 is the very edge 1 came by. It is the same road seen from the other end, so we skip it.
- edges
- e0 0-1, e1 1-2, e2 2-0, e3 2-3
- queue
- [2]
- cameBy[1]
- e0
- looking at
- e1 (1-2)
- result
- true
8Edge e1 leads to 2, which is already visited, and e1 is not the edge 1 came by. That is a second route to 2, so there is a cycle: 0-1-2-0.
Let us read the important frames back. In the fourth and fifth frames vertex 0 discovers 1 along e0 and 2 along e2, and both notes go into cameBy. These two edges are the first branches of the BFS tree.
The seventh frame is the trap made visible. Standing at 1, the first edge in its list is e0, leading back to 0, which is visited. If we stopped here we would report a false cycle on every graph. But cameBy[1] is e0, so we know it is the road 1 came by, and we skip it.
In the last frame the next edge is e1, leading to 2. Vertex 2 is already visited, and e1 is not the road 1 came by, so 2 has two routes from 0: directly along e2, and through 1 along e0 and e1. Together they form the triangle, and the method returns true without ever looking at e3 or vertex 3.
6The complete Java program
Here is the full program. main tests our triangle, the tree, a graph in two pieces whose loop does not touch vertex 0, two parallel edges between 0 and 1, and a graph with no edges. Each comment shows what that line prints.
Let us read hasCycle in the order it runs. First it builds adj, one list per vertex. Each edge, numbered by its position id, adds an entry at both ends, because the road is two-way, and each entry holds the neighbour and the edge number, which is what lets us recognise the road we arrived by.
Next come visited and cameBy, and the outer for loop over start. If start was reached by an earlier search we skip it; otherwise we mark it visited, set cameBy[start] to -1, because a starting vertex came by no road and -1 matches no real edge, and put it in a fresh queue.
Inside the while loop, queue.poll() takes the oldest vertex u, and we look along each of its entries. The first check skips the entry whose edge number equals cameBy[u], the road back to where u came from. The second check is the discovery: if v is already visited, we have a second route to v and return true. Otherwise v is new, so we mark it, record the edge in cameBy[v] and add it to the queue.
If every search finishes without a second route, we return false. So main prints true for the triangle and false for the tree. It prints true for the piece 2, 3, 4, which the outer loop reaches, and true for the parallel edges, because the second road from 0 finds 1 already visited. The graph with no edges prints false.
7How much it costs, and the cases at the edges
Let us count on the example first. Building adj touched each of the 4 edges twice, 8 entries. The search then took 2 vertices from the queue and examined 4 entries before returning. Without a cycle it would take every vertex once and examine all 8 entries. For V vertices and E edges that is O(V + E) time, and we cannot do better, because the answer may depend on any edge.
The neighbour lists hold 2E entries, and visited, cameBy and the queue hold at most V values each, so the space is O(V + E).
| Approach | Time | Extra space |
|---|---|---|
| Close each road and search again | O(E * (V + E)) or worse | O(V) |
| One BFS per piece, skip the road we came by | O(V + E) | O(V + E) |
| Union-find over the edge list | nearly O(E) | O(V) |
The edge cases are handled by the same code. A graph with no edges builds empty lists, every vertex starts a trivial search, and we return false. A loop in a later piece is found when the outer loop reaches it. A self-loop {u, u} adds two entries to u's own list, and the first one finds u visited along an edge that is not the one u came by, so it is reported. Parallel edges are caught by the edge-number rule, as main shows.
Recursive DFS with the same parent-road rule works as well as BFS, but each step of a long path waits on the call stack, and a path of 100,000 vertices can throw a StackOverflowError. BFS, or a DFS with its own stack, is the safer default.
8Follow-up questions
How does union-find detect the cycle?
Union-find, also called disjoint set union, keeps every vertex in a group, with one vertex acting as the group's representative, much like each team having a captain. At the start every vertex is its own group. We read the edges one by one. If both ends of an edge already have the same representative, they are already connected, so this edge closes a loop and we return true. Otherwise we merge their groups. On our example, 0-1 merges 0 and 1, 1-2 adds 2, and 2-0 finds 2 and 0 already in one group. With path compression and union by rank it runs in nearly O(E) time and O(V) space, and it suits edges that arrive one at a time.
Does the same check work for a directed graph?
No. With one-way roads, reaching a visited vertex is not enough. In 0 -> 1, 0 -> 2, 2 -> 1, vertex 1 is reached twice, but there is no way to come back to where we started, so no cycle. For directed graphs we use DFS with three states, not yet seen, on the current path, and finished, and report a cycle only when we meet a vertex still on the current path. Kahn's topological sort is the other choice: it repeatedly removes vertices with no incoming edges, and the graph has a cycle exactly when some vertices are never removed.
How would you return the cycle itself, not just true?
Record the parent vertex of each vertex as well as the edge it came by. When the edge from u to v reports a second route, walk up the parents from u and from v until the two walks meet at a common vertex. The vertices on those two walks, joined by the edge u-v, are the cycle. On our example u is 1 and v is 2; both parents are 0, so the cycle is 0, 1, 2 and back to 0.
9Conclusion
We detected a cycle in an undirected graph with one BFS per piece of the graph. Each vertex remembers the edge it was first reached by, so the road back to where we came from is skipped, and any other edge that reaches a visited vertex is a second route and closes a loop. That takes O(V + E) time and space. The clue to remember is a question about connections in a graph: walk it once, and remember that the edges a traversal uses form a tree, so any edge left over makes a cycle.
Open with
Let me confirm: the graph is undirected, it may be in several pieces, and a self-loop or two parallel edges count as cycles. A brute force closes each edge in turn and checks whether its ends are still connected, which is O(E times V plus E).
Then, if they want more
Instead I use one traversal. A BFS reaches each new vertex along exactly one edge, and those edges form a tree, so any other edge that leads to an already visited vertex closes a cycle. The trap is that every edge appears in both endpoints' lists, so the edge I arrived by always leads back to a visited vertex.
I store the edge index with each neighbour and keep cameBy, the edge that discovered each vertex, and I skip exactly that edge. Skipping the edge rather than the parent vertex also catches parallel edges. I mark vertices visited when I enqueue them, and an outer loop starts a new BFS from every unvisited vertex for disconnected graphs.
On the triangle, 0 discovers 1 and 2, then 1 skips the edge back to 0 and finds 2 already visited, so I return true. That is O(V plus E) time and space. Union-find is an alternative that reports a cycle when an edge joins two vertices already in the same group.
About this answer
- Last updated
- 15 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 43 times in that collection. How it is counted
- Official documentation
- ArrayDeque (Java 21), ArrayList (Java 21), java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Determine whether an undirected graph contains a cycle.": https://scrivio-interview-library.netlify.app/data-structures/solutions/determine-whether-an-undirected-graph-contains-a-cycle-e123f0/