Checking Existence of Edge Length Limited Paths - Problem

An undirected graph of n nodes is defined by edgeList, where edgeList[i] = [ui, vi, disi] denotes an edge between nodes ui and vi with distance disi. Note that there may be multiple edges between two nodes.

Given an array queries, where queries[j] = [pj, qj, limitj], your task is to determine for each queries[j] whether there is a path between pj and qj such that each edge on the path has a distance strictly less than limitj.

Return a boolean array answer, where answer.length == queries.length and the jth value of answer is true if there is a path for queries[j], and false otherwise.

Input & Output

Example 1 — Basic Connectivity
$ Input: n = 3, edgeList = [[0,1,2],[1,2,4],[2,0,8],[1,0,16]], queries = [[0,1,10],[0,2,5]]
Output: [true,false]
💡 Note: For query [0,1,10]: Can use edge [0,1,2] since 2 < 10. For query [0,2,5]: Edge [1,2,4] works (4 < 5) but need path 0→1→2, so also need [0,1,2] (2 < 5) ✓. Actually there's direct edge [2,0,8] but 8 > 5. Path 0→1→2 uses edges with weights 2,4 both < 5, so answer is true.
Example 2 — No Valid Path
$ Input: n = 5, edgeList = [[0,1,10],[1,2,5],[2,3,20],[3,4,15]], queries = [[0,4,14]]
Output: [false]
💡 Note: To go from 0 to 4, must use path 0→1→2→3→4. Edge weights are [10,5,20,15]. Since edge [2,3,20] has weight 20 ≥ 14, no valid path exists.
Example 3 — Multiple Valid Paths
$ Input: n = 4, edgeList = [[0,1,3],[1,3,1],[0,2,7],[2,3,2]], queries = [[0,3,8]]
Output: [true]
💡 Note: Two paths exist: 0→1→3 (weights 3,1 both < 8) and 0→2→3 (weights 7,2 both < 8). Both paths are valid, so answer is true.

Constraints

  • 1 ≤ 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

Visualization

Tap to expand
Edge Length Limited Paths: Check Connectivity Under Weight Limits0123w=2w=4w=8w=16Query [0,1,10]Can use edge 0→1 (w=2 < 10)Result: TRUEQuery [0,2,5]Path 0→1→2 needs w=2,4 < 5 ✓Result: TRUEKey InsightSort edges and queriesProcess offline with Union-Find💡 Process queries offline by building connectivity incrementally
Understanding the Visualization
1
Input Graph
Graph with weighted edges and connectivity queries
2
Filter Edges
For each query, consider only edges under weight limit
3
Check Path
Determine if valid path exists between query nodes
Key Takeaway
🎯 Key Insight: Sort edges and queries to process them offline, building connectivity incrementally with Union-Find for optimal performance
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
23.0K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen