Python 1697.py
class Solution:
def distanceLimitedPathsExist(self, n: int, edgeList: List[List[int]], queries: List[List[int]]) -> List[bool]:
# idea: incremental union-find, connect short edges first and evaluate related queries
# union-find, copied from problem 721, simplified
def find(x):
if parent[x] != x:
parent[x] = find(parent[x]) # path compression
return parent[x]
def union(x, y):
parent[find(x)] = find(y)
parent = list(range(n))
edges = [] # min-heap, shortest edges first
for u, v, weight in edgeList:
heappush(edges, ( weight, u, v ))
size = len(queries)
result = [ 0 ] * size
for i in sorted(range(size), key = lambda x : queries[x][2]): # queries with low limit come first
p, q, limit = queries[i]
# add all edges up to the current limit
while edges and edges[0][0] < limit:
weight, u, v = heappop(edges)
union(u, v)
# same (sub)net ?
result[i] = find(p) == find(q)
return result
Difficulty
and has an acceptance rate of about 63% (80k+ submissions).
Typical patterns to solve this problem:
- Array
- Graph
- Sorting
- Two Pointers
- Union Find
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the “distance limited paths existence” problem by processing edges in increasing order of weight and answering each query after all edges whose weight is strictly smaller than the query’s limit have been merged. A disjoint-set (union-find) structure maintains connectivity information, allowing each query to be answered in near-constant time once the relevant edges are incorporated.
Key Steps
The algorithm can be broken down into distinct phases, each reflected in a concise code fragment.
Initialize the union-find structure
The parent array holds the representative of each node. The find function implements path compression, while union links two components.
def find(x):
if parent[x] != x:
parent[x] = find(parent[x]) # path compression
return parent[x]
def union(x, y):
parent[find(x)] = find(y)
parent = list(range(n))
Collect edges in a min-heap
All edges are pushed onto a heap as triples (weight, u, v). The heap guarantees that the smallest remaining edge can be retrieved in O(log m) time.
edges = [] # min-heap, shortest edges first
for u, v, weight in edgeList:
heappush(edges, (weight, u, v))
Sort queries by their distance limit Queries are reordered so that those with smaller limits are processed first. The original index is preserved to place results back in the correct order.
size = len(queries)
result = [0] * size
for i in sorted(range(size), key=lambda x: queries[x][2]): # low limit first
p, q, limit = queries[i]
Incrementally add eligible edges Before answering a query, the algorithm extracts edges from the heap while their weight is strictly less than the current query’s limit, merging their endpoints.
while edges and edges[0][0] < limit:
weight, u, v = heappop(edges)
union(u, v)
Answer the query
After all qualifying edges have been merged, the connectivity of the query’s endpoints is checked via find. The boolean result is stored at the original query position.
result[i] = find(p) == find(q)
Return the assembled answers Finally, the list of booleans, aligned with the input order, is returned.
return result
Edge Cases Handled
The logic naturally accommodates several boundary conditions:
- Queries with a limit lower than any edge weight - The
whileloop never executes, leaving the union-find in its initial state. The subsequentfindcalls correctly report that only a node is connected to itself. - Queries with a limit higher than all edge weights - All edges are drained from the heap before the first such query, resulting in a fully merged graph. Connectivity checks then reflect the ultimate component structure.
- Self-queries where the source and destination are identical - Since each node is initially its own parent,
find(p) == find(q)evaluates toTrueregardless of edge processing. - Empty edge list - The heap remains empty, so no unions occur. Queries are answered solely based on whether the source equals the destination.
- Empty query list - The outer loop iterates zero times, and an empty result list is returned without error.
- Duplicate edges with identical weights - Each duplicate is pushed onto the heap and processed in turn; redundant unions have no adverse effect because the union-find structure ignores already-connected components.
Performance Optimizations
Several deliberate choices keep the execution efficient:
- Min-heap for edge ordering - By storing edges in a heap, the algorithm extracts the next smallest edge in logarithmic time, avoiding a full sort of the edge list.
- Sorting queries once - Queries are sorted by their limit only a single time. This ordering enables the incremental addition of edges without revisiting previously processed edges.
- Path compression in
find- The recursive assignmentparent[x] = find(parent[x])flattens the tree structure on each lookup, dramatically reducing the cost of subsequentfindoperations. - In-place union without rank heuristics - Although rank or size heuristics are omitted, the combination of path compression and the incremental nature of edge insertion yields near-constant amortized union cost for the problem’s typical input sizes.
- Pre-allocation of the result array - The result list is created with the exact required length, eliminating dynamic resizing during query processing.
Together, these techniques ensure that the algorithm scales well with large numbers of nodes, edges, and queries, delivering answers with minimal overhead beyond the essential union-find operations.
ELI5 - Simplified Explanation
Imagine you have a big set of islands and you want to know if there is a bridge path connecting two specific islands that only uses bridges smaller than a certain size.
To solve this, the code starts by sorting all the bridges by how tiny they are. It also keeps track of which islands are connected to each other, like drawing lines between them until they form little neighborhoods.
The code looks at the smallest requested limit first. It takes all the tiny bridges that fit under that limit and connects the islands together. Once those islands are joined in a neighborhood, it checks if the two islands you care about are sitting in the same neighborhood. If they are, it means there is a path between them using only those small bridges. It keeps doing this for every request, adding more bridges as the limits get bigger, until every single request is answered.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | |||||||
| leetcode.ca | C++ | Java | Python | Go | Rust | ||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 1724: Checking Existence of Edge Length Limited Paths II
- problem 2421: Number of Good Paths
- problem 2492: Minimum Score of a Path Between Two Cities
Solved On The Same Day
- problem 1319: Number of Operations to Make Network Connected
- problem 1465: Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
- problem 1477: Find Two Non-overlapping Sub-arrays Each With Target Sum
- problem 1482: Minimum Number of Days to Make m Bouquets
- problem 1488: Avoid Flood in The City
- problem 1524: Number of Sub-arrays With Odd Sum
- problem 1546: Maximum Number of Non-Overlapping Subarrays With Sum Equals Target
- problem 1562: Find Latest Group of Size M
- problem 1567: Maximum Length of Subarray With Positive Product
- problem 1320: Minimum Distance to Type a Word Using Two Fingers
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality