GRPH-P4

Find a cycle

Practice 4 of 7Graphs12 tests

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

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

12 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2No cycleNot run
3Two ways to one placeNot run
4An edge to itselfNot run
5There and backNot run
6A cycle 0 cannot reachNot run
7A cycle after a finished partNot run
81,000 verticesNot run
9A path of 100,000 with an edge backNot run
1040 layers of twoNot run
11100,000 vertices, no cycleNot run
12100,000 vertices with cyclesNot run