DSUF-P3

The road that closes a loop

Practice 3 of 5Union-find9 tests

The problem

There are n places, numbered 0 to n - 1, and no roads. Roads are built one at a time, in the order of the list. A road (a, b) connects a and b in both directions. Return the position in the list of the first road that closes a loop: a road between two places that could already reach each other. Return -1 if no road does.

first_cycle(4, [(0, 1), (1, 2), (2, 0), (2, 3)])    # 2
first_cycle(4, [(0, 1), (1, 2), (2, 3)])            # -1

A road from a place to itself, (a, a), closes a loop at once. So does a second road between the same two places.

Some tests join long chains. Write find with a loop, or make sure your trees stay short (lessons 2 and 3): a recursive find on a path of 100,000 nodes stops with RecursionError.

Limits

  • Up to 200,000 places and 200,000 roads.

Builds on DSUF-5 Applications.

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.

9 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2No cycleNot run
3A road to itselfNot run
4The same road twiceNot run
5Lesson 5's roadsNot run
6Separate groupsNot run
7No roadsNot run
8200,000 placesNot run
9A long chainNot run