3532. Path Existence Queries in a Graph I
- Array
- Union Find
- Prefix Sum
TIME
O(n + q)
SPACE
O(n)
Intuition
nums is sorted, which collapses the whole graph structure: a connected component is always a contiguous range of indices. Two neighbors i and i+1 are joined iff nums[i+1] - nums[i] <= maxDiff. If that consecutive gap exceeds maxDiff, nothing can bridge it, any edge crossing the gap connects two values at least that far apart (sorted order), so it also exceeds maxDiff. Hence the components are exactly the maximal runs where every consecutive gap is <= maxDiff.
Approach
- Build a component id array in one pass:
comp[0] = 0.comp[i] = comp[i-1]ifnums[i] - nums[i-1] <= maxDiff, elsecomp[i-1] + 1.
- For each query
[u, v], answercomp[u] == comp[v].
Complexity
- Time: O(n + q)
- Space: O(n), the component-id array
Edge Cases
- Self query
[u, u]→ alwaystrue maxDiff = 0→ nodes connected only if their values are exactly equal (equal adjacent values still merge)- All equal values → one component → every query
true - Single node → trivially its own component
Code
from typing import List
class Solution:
def pathExistenceQueries(self, n: int, nums: List[int], maxDiff: int, queries: List[List[int]]) -> List[bool]:
"""
3532. Path Existence Queries in a Graph I
Time: O(n + q)
Space: O(n)
"""
# Component id: increments whenever a consecutive gap exceeds maxDiff.
comp = [0] * n
for i in range(1, n):
comp[i] = comp[i - 1] + (1 if nums[i] - nums[i - 1] > maxDiff else 0)
return [comp[u] == comp[v] for u, v in queries]/**
* 3532. Path Existence Queries in a Graph I
* Time: O(n + q)
* Space: O(n)
*/
class Solution {
public boolean[] pathExistenceQueries(int n, int[] nums, int maxDiff, int[][] queries) {
// Component id: increments whenever a consecutive gap exceeds maxDiff.
int[] comp = new int[n];
for (int i = 1; i < n; i++) {
comp[i] = comp[i - 1] + (nums[i] - nums[i - 1] > maxDiff ? 1 : 0);
}
boolean[] ans = new boolean[queries.length];
for (int i = 0; i < queries.length; i++) {
ans[i] = comp[queries[i][0]] == comp[queries[i][1]];
}
return ans;
}
}