Graph Theory37 sections · 1633 units
Open in Course

LeetCode 1697 Edge Limited Paths - Implementation Plan

Sorting Everything

Here is the offline query implementation:

function edgeLimitedPaths(n, edges, queries):
    // Sort edges by weight
    sortedEdges = sort edges by weight ascending

    // Sort queries by limit, keeping original indices
    indexedQueries = [(limit, u, v, idx) for idx, (u, v, limit) in enumerate(queries)]
    sort indexedQueries by limit ascending

    parent = array [0, 1, 2, ..., n-1]
    answer = array of size queries.length

    edgePtr = 0

    for (limit, u, v, idx) in indexedQueries:
        // Add all edges with weight < limit
        while edgePtr < edges.length and sortedEdges[edgePtr].weight < limit:
            (a, b, w) = sortedEdges[edgePtr]
            union(a, b)
            edgePtr = edgePtr + 1

        // Check if u and v are connected
        answer[idx] = (find(u) == find(v))

    return answer

Time: O((E+Q)logE)O((E + Q) \log E) for sorting. Space: O(n)O(n) for Union-Find.