Checking Existence of Edge Length Limited Paths - Problem
You're working with a weighted undirected graph where nodes represent cities and edges represent roads with specific distances. Your task is to answer multiple queries asking: "Can I travel from city A to city B using only roads shorter than a given limit?"
Given:
edgeList: An array whereedgeList[i] = [ui, vi, disi]represents a road between citiesuiandviwith distancedisiqueries: An array wherequeries[j] = [pj, qj, limitj]asks if there's a path frompjtoqjusing only edges with distance strictly less thanlimitj
Goal: Return a boolean array indicating whether each query has a valid path.
Note: Multiple edges between the same pair of nodes are allowed, and you need to find if any valid path exists, not necessarily the shortest one.
Input & Output
example_1.py โ Basic Graph
$
Input:
n = 3, edgeList = [[0,1,2],[1,2,4],[2,0,8],[1,0,16]], queries = [[0,1,2],[0,2,5]]
โบ
Output:
[false, true]
๐ก Note:
For query [0,1,2]: No edge between 0 and 1 has weight < 2. For query [0,2,5]: Path 0โ1โ2 uses edges with weights 2 and 4, both < 5.
example_2.py โ Disconnected Components
$
Input:
n = 5, edgeList = [[0,1,10],[1,2,5],[2,3,9],[3,4,13]], queries = [[0,4,14],[1,4,13]]
โบ
Output:
[true, false]
๐ก Note:
For query [0,4,14]: Path 0โ1โ2โ3โ4 uses edges [10,5,9,13], all < 14. For query [1,4,13]: Edge 3โ4 has weight 13, not < 13.
example_3.py โ Multiple Edges
$
Input:
n = 2, edgeList = [[0,1,5],[0,1,3],[0,1,7]], queries = [[0,1,4],[0,1,6]]
โบ
Output:
[true, true]
๐ก Note:
Multiple edges exist between nodes 0 and 1. For both queries, the edge with weight 3 can be used since 3 < 4 and 3 < 6.
Visualization
Tap to expand
Understanding the Visualization
1
Initialize
Start with isolated cities, sort roads by danger level
2
Process Query
Add all roads with danger level below current query threshold
3
Connect Cities
Use Union-Find to efficiently connect cities via safe roads
4
Check Route
Verify if emergency vehicle can reach destination
Key Takeaway
๐ฏ Key Insight: By sorting both edges and queries, we can process them incrementally, building connectivity efficiently with Union-Find while avoiding redundant work across similar queries.
Time & Space Complexity
Time Complexity
O(Q ร (V + E))
Q queries, each requiring O(V + E) graph traversal in worst case
โ Linear Growth
Space Complexity
O(V)
Space for visited array and recursion stack during DFS
โ Linear Space
Constraints
- 2 โค n โค 105
- 0 โค edgeList.length, queries.length โค 105
- edgeList[i].length == 3
- queries[j].length == 3
- 0 โค ui, vi, pj, qj โค n - 1
- ui โ vi
- pj โ qj
- 1 โค disi, limitj โค 109
- Note: There may be multiple edges between two nodes
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code