Bank app~30 min2s · 256 MBtarget O(n × (n + m)) time, O(n + m) spacebfs
You work on a fraud team of a bank. Accounts are numbered 0 to n - 1. A transfer moves money one way, from one account to another. A loop of transfers is a chain that ends at the account where it began.
Money that goes round a loop can hide where it came from. Short loops are the most suspicious, because they are the cheapest to run.
Your team lead asks: "How many transfers does the shortest loop have?" The bank has up to 500 accounts in the case under review, and up to 2,000 transfers.
Write shortest_transfer_loop(n, transfers).
transfers[k] = [a, b] is a one-way transfer from account a to account b. Transfers can repeat, and a can equal b.-1 when there is no loop.Input: n = 5, transfers = [[0, 1], [1, 2], [2, 3], [3, 0], [2, 4], [4, 2]]
Output: 2The accounts 0, 1, 2 and 3 form a ring of 4 transfers, and accounts 2 and 4 send money to each other. The shortest loop through each account:
| Account | Shortest loop through it |
|---|---|
| 0 | 4 |
| 1 | 4 |
| 2 | 2 |
| 3 | 4 |
| 4 | 2 |
The shortest loop of all is 2, 4, 2, with 2 transfers.
Input: n = 4, transfers = [[0, 1], [1, 2], [0, 2], [2, 3]]
Output: -1Every transfer goes to a higher number, so money never returns to its start.
Input: n = 3, transfers = [[1, 1]]
Output: 1An account that pays itself is a loop of 1 transfer.
1 ≤ n ≤ 5000 ≤ len(transfers) ≤ 2,0000 ≤ transfers[k][0], transfers[k][1] < nFollowing every chain of transfers is exponential: with about 4 transfers out of each account, the chains of length 20 already number about a trillion. A search from one account costs about 2,500 steps. Searching from each of the 500 accounts costs about 1,250,000 steps, which is fast.