Checking Existence of Edge Length Limited Paths II - 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, and the graph may not be connected.
Implement the DistanceLimitedPathsExist class:
DistanceLimitedPathsExist(int n, int[][] edgeList)Initializes the class with an undirected graph.boolean query(int p, int q, int limit)Returnstrueif there exists a path fromptoqsuch that each edge on the path has a distance strictly less thanlimit, and otherwisefalse.
Input & Output
Example 1 — Basic Graph
$
Input:
n = 4, edges = [[0,1,3],[1,2,1],[2,3,1]], queries = [[0,3,2],[0,3,4]]
›
Output:
[false,true]
💡 Note:
Query 1: path 0→3 with limit 2. Only edge (1,2) and (2,3) have weight < 2, but 0 is not connected. Query 2: path 0→3 with limit 4. Edges (0,1), (1,2), (2,3) all have weight < 4, so path 0→1→2→3 exists.
Example 2 — No Valid Path
$
Input:
n = 3, edges = [[0,1,10],[1,2,5]], queries = [[0,2,3]]
›
Output:
[false]
💡 Note:
Query: path 0→2 with limit 3. All edges have weight ≥ 3, so no valid path exists.
Example 3 — Direct Connection
$
Input:
n = 2, edges = [[0,1,2]], queries = [[0,1,3],[0,1,1]]
›
Output:
[true,false]
💡 Note:
Query 1: path 0→1 with limit 3. Edge weight 2 < 3, so direct path exists. Query 2: path 0→1 with limit 1. Edge weight 2 ≥ 1, so no valid path.
Constraints
- 2 ≤ n ≤ 104
- 0 ≤ edges.length ≤ 104
- edges[i].length == 3
- 0 ≤ ui, vi < n
- ui ≠ vi
- 0 ≤ disi ≤ 109
- 0 ≤ queries.length ≤ 104
- queries[j].length == 3
- 0 ≤ pj, qj < n
- pj ≠ qj
- 0 ≤ limitj ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input Graph
Graph with weighted edges and connectivity queries
2
Filter Edges
Keep only edges with weight < query limit
3
Check Connectivity
Determine if path exists between query nodes
Key Takeaway
🎯 Key Insight: Sort edges and queries to process offline, avoiding repeated graph reconstruction
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code