Ad platform~20 min2s · 256 MBtarget O(n + m) time, O(n + m) spacecycle-detection
You work on an ad platform. When a campaign has spent its budget for the hour, it hands new ad requests over to another campaign. The campaigns are numbered 0 to n - 1.
A hand-off [a, b] is one-way: campaign a passes requests to campaign b, and b does not pass them back unless a hand-off says so. If the hand-offs form a loop, a request can be passed round for ever and is never shown. Before a new set of rules goes live, the platform must check that no loop exists.
Write has_overflow_loop(n, handoffs).
n is the number of campaigns.handoffs[i] = [a, b] is a one-way hand-off from campaign a to campaign b.true when following hand-offs can lead from a campaign back to itself, and false otherwise.Input: n = 6, handoffs = [[0, 1], [1, 2], [2, 3], [3, 1], [3, 4], [5, 0]]
Output: trueCampaigns 1, 2 and 3 hand off in a circle. Count the hand-offs each campaign receives, then settle campaigns that receive none.
| Step | Settle | Queue after | Hand-offs received by campaigns 0 to 5 |
|---|---|---|---|
| start | 5 | 1, 2, 1, 1, 1, 0 | |
| 1 | 5 | 0 | 0, 2, 1, 1, 1, 0 |
| 2 | 0 | 0, 1, 1, 1, 1, 0 |
The queue is empty with only 2 of 6 campaigns settled, so there is a loop.
Input: n = 4, handoffs = [[0, 1], [0, 2], [1, 3], [2, 3]]
Output: falseTwo routes meet at campaign 3. That is not a loop, because no route returns to where it started.
Input: n = 1, handoffs = [[0, 0]]
Output: trueA campaign that hands requests to itself is a loop of one.
1 ≤ n ≤ 100,0000 ≤ len(handoffs) ≤ 100,000, and every row is [a, b] with 0 ≤ a, b < nThere can be 100,000 campaigns and 100,000 hand-offs. Removing campaigns one at a time, with a full check of every hand-off after each removal, is far beyond a billion steps. The answer must touch each campaign and hand-off a few times: n + m.