The problem
A directed graph has vertices 0 to n − 1, and each edge (u, v) goes one way, from u to v. If the graph has a cycle (a route that follows edges and comes back to where it started), return one, as a list of different vertices [v0, v1, …, vk] where each vertex has an edge to the next, and the last has an edge back to the first. Otherwise return None.
edges = [(0, 1), (1, 2), (2, 3), (3, 1), (3, 4)]
find_cycle(5, edges) # [1, 2, 3]
diamond = [(0, 1), (0, 2), (1, 3), (2, 3)]
find_cycle(4, diamond) # None
find_cycle(2, [(0, 1), (1, 1)]) # [1]
Any cycle is accepted, starting from any of its vertices. An edge from a vertex to itself is a cycle of one vertex. The tests follow your cycle’s edges to check it.
Limits
- Up to 100,000 vertices and 200,000 edges.
- Paths can be 100,000 vertices deep, so use your own stack (as in P3). One test has 2⁴⁰ different paths: each vertex must be searched only once. The big tests have 3 seconds each.
Builds on GRPH-4 Cycle detection.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | The example | Not run | |
| 2 | No cycle | Not run | |
| 3 | Two ways to one place | Not run | |
| 4 | An edge to itself | Not run | |
| 5 | There and back | Not run | |
| 6 | A cycle 0 cannot reach | Not run | |
| 7 | A cycle after a finished part | Not run | |
| 8 | 1,000 vertices | Not run | |
| 9 | A path of 100,000 with an edge back | Not run | |
| 10 | 40 layers of two | Not run | |
| 11 | 100,000 vertices, no cycle | Not run | |
| 12 | 100,000 vertices with cycles | Not run |