#3534
Path Existence Queries in a Graph II
HardArrayTwo PointersBinary SearchDynamic ProgrammingGreedyBit ManipulationGraph TheorySortingGraph TraversalUnion-Find
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n + m) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n + m)Space O(n)
Sort nodes based on their values and use a two-pointer technique to efficiently find connected components. This reduces unnecessary checks.
⚙️
Algorithm
3 steps- 1Step 1: Create a list of nodes sorted by their values in nums.
- 2Step 2: Use two pointers to group nodes into connected components based on maxDiff.
- 3Step 3: For each query, check if both nodes belong to the same component and return the distance.
solution.py12 lines
1def min_distance_optimal(n, nums, maxDiff, queries):
2 sorted_nodes = sorted(range(n), key=lambda x: nums[x])
3 components = [-1] * n
4 component_id = 0
5 for i in range(n):
6 if components[sorted_nodes[i]] == -1:
7 j = i
8 while j < n and nums[sorted_nodes[j]] - nums[sorted_nodes[i]] <= maxDiff:
9 components[sorted_nodes[j]] = component_id
10 j += 1
11 component_id += 1
12 return [1 if components[u] == components[v] else -1 for u, v in queries]ℹ
Complexity note: Sorting takes O(n log n), and processing each query is O(1) after that.
- 1Sorting helps group nodes efficiently.
- 2Two-pointer technique reduces unnecessary checks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.