Problem 1697

Abstract / Summary

Check if a path exists between two nodes where each edge's weight does not exceed a given limit.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
33 lines | 1174 bytes | submitted May 3, 2024 | GitHub   33% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 63% (80k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Graph
  • Sorting
  • Two Pointers
  • Union Find
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 while loop never executes, leaving the union-find in its initial state. The subsequent find calls 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 to True regardless 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 assignment parent[x] = find(parent[x]) flattens the tree structure on each lookup, dramatically reducing the cost of subsequent find operations.
  • 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.22 | σ = 1.71

Complexity Analysis

Time: loglinear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
23 links | 13 authors | 8 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

11 solutions   May 3, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • 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