Monitoring~20 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-160linked-lists · two-pointers
A monitoring system escalates an alert along a chain of levels. The levels sit in a table: slot i holds after[i], the level that gets the alert next, or -1 when i is the top level.
Two teams start at different levels, and their chains join and share every level from some point up. You need the first level that both chains reach. The chains never loop, and a table can hold 100,000 levels.
Write first_shared_level(after, first, second).
after is the table. Each value is -1 or a level number below the length of the table.first and second are the levels where the two chains start.after from each start. Return the first level that appears on both chains, counted along the first chain. Return -1 when the chains never meet.Input: after = [1, 2, 5, 4, 5, 6, -1], first = 0, second = 3
Output: 5| Step | a | b | What happens |
|---|---|---|---|
| start | 0 | 3 | a walks 0 → 1 → 2 → 5 → 6, and b walks 3 → 4 → 5 → 6 |
| 1 | 1 | 4 | one step each |
| 2 | 2 | 5 | b is on the shared level 5 already, and a is still on its own part |
| 3 | 5 | 6 | a is on the shared level 5, but b is one step ahead of it |
| 4 | 6 | -1 | b falls off the end of its chain |
| 5 | -1 | 0 | a falls off the end, and b starts on the first chain |
| 6 | 3 | 1 | a starts on the second chain |
| 7 | 4 | 2 | |
| 8 | 5 | 5 | both are on level 5: return 5 |
Chain a has 5 levels and chain b has 4, so they are out of step. Each walker takes the other chain after its own, and both then walk the same total distance. For a it is 3 own levels, 2 shared levels, the step onto -1 and 2 levels of the second chain: 8 steps.
Input: after = [1, -1, 3, -1], first = 0, second = 2
Output: -1The chains 0 → 1 and 2 → 3 share no level. Both walkers reach -1 on the same step, so they stand on the same slot, -1.
Input: after = [1, 2, -1], first = 1, second = 1
Output: 1Both chains start on the same level, so it is the first shared one.
1 ≤ length of after ≤ 10^5-1 ≤ after[i] ≤ length of after - 10 ≤ first, second ≤ length of after - 1Each chain can have tens of thousands of levels. A plan that checks every level of one chain against every level of the other makes up to n × m comparisons. That is about 2.4 × 10^9 for chains of 80,000 and 60,000 levels, which is too slow.
Writing one chain into a set fixes the time, but the set holds a whole chain. Walking both chains with two pointers needs only a fixed amount of memory: O(n) time and O(1) extra space.
A note on the tests: the judge measures time, not extra memory, so the set passes and only the pairwise check times out. The fixed-memory walk is the point of the problem.