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) Returns true if there exists a path from p to q such that each edge on the path has a distance strictly less than limit, and otherwise false.

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
Edge Weight Limited Path Queries0123w=3w=1w=1SourceTargetQuery: Path from 0 to 3 with limit = 2✗ Edge 0-1 (weight 3 ≥ 2) excluded✓ Edges 1-2, 2-3 (weight 1 < 2) includedResult: false (0 disconnected from {1,2,3})
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
Asked in
Google 25 Facebook 18 Amazon 15 Microsoft 12
28.5K Views
Medium Frequency
~35 min Avg. Time
892 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