1518. Earliest Link Moments
A telecom company has n towns numbered 0 to n - 1. Cables are laid one per day in the order given: edges[i] = [a, b] joins towns a and b on day i + 1. Cables are never removed, and repeated or self-joining cables are allowed but add nothing new.
Each entry queries[j] = [u, v] asks for the smallest day p such that towns u and v can reach each other using only the first p cables. Answer 0 when u == v, and -1 when they are never connected. Return an array with one answer per query, in query order.
Hint: whether a pair is connected after p days is monotone in p, so you can run a parallel binary search over all queries, or record the day at which each union-find merge happens and read the answer off the merge tree. Use an iterative find. Aim for O((m + q) log n) time and O(n + m + q) space.
Example 1
- Input:
- n = 5edges = [[0,1],[3,4],[1,2],[2,3]]queries = [[0,2],[0,4],[3,3],[1,4]]
- Output:
- [3,4,0,4]
- Explanation:
Towns 0 and 2 join on day 3, towns 0 and 4 and towns 1 and 4 join on day 4, and a town is linked to itself from day 0.
Example 2
- Input:
- n = 3, edges = [[0,1]], queries = [[0,2],[1,0]]
- Output:
- [-1,1]
- Explanation:
Town 2 never gets a cable, so the first query is -1, while towns 1 and 0 are linked on day 1.
Example 3
- Input:
- n = 2, edges = [], queries = [[1,1],[0,1]]
- Output:
- [0,-1]
- Explanation:
With no cables only the self-query is answerable; the other pair is never connected.
Constraints
1 ≤ n ≤ 5 * 104
0 ≤ edges.length ≤ 5 * 104
1 ≤ queries.length ≤ 5 * 104
0 ≤ u, v < n; use an iterative find (no deep recursion)
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 6,000 msC++ 1,500 msJava 3,000 msJavaScript 3,000 msTypeScript 3,000 ms
Expected complexity
- Time
- O((m + q) log n)
- Space
- O(n + m + q)