The problem
Split all n junctions into their strongly connected groups. Return a list group with one number per junction. Two junctions get the same number exactly when each can reach the other. Number the groups 0, 1, 2, … with no number missing, and in an order that every street respects: for every street (u, v), group[u] <= group[v]. That order is a topological order of the graph of groups (lesson 1).
streets = [(0, 1), (1, 4), (4, 0), (5, 4), (5, 6),
(1, 2), (2, 3), (3, 7), (7, 6), (6, 2)]
scc(8, streets) # [1, 1, 2, 2, 1, 0, 2, 2]
scc(4, [(2, 3), (0, 1), (1, 2)]) # [0, 1, 2, 3]
When several numberings are right (groups with no street between them can come in either order), any of them is accepted. The tests check the numbers you return: the groups, the order, and no gaps.
Limits
- Up to 100,000 junctions and 160,000 streets.
- The search can go 100,000 levels deep. The big tests have 4 seconds each.
Builds on CONN-2 Kosaraju and Tarjan.
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 | A one-way chain | Not run | |
| 3 | No streets | Not run | |
| 4 | One junction | Not run | |
| 5 | Loops and repeated streets | Not run | |
| 6 | Two loops joined both ways | Not run | |
| 7 | A cross street to a finished group | Not run | |
| 8 | A chain of 100,000 | Not run | |
| 9 | A ring of 100,000 | Not run | |
| 10 | 80,000 random streets | Not run | |
| 11 | 20,000 small groups | Not run |