[LeetCode] Path Existence Queries in a Graph I

3532. Path Existence Queries in a Graph I

You are given an integer n representing the number of nodes in a graph, labeled from 0 to n - 1.

You are also given an integer array nums of length n sorted in non-decreasing order, and an integer maxDiff.

An undirected edge exists between nodes i and j if the absolute difference between nums[i] and nums[j] is at most maxDiff (i.e., |nums[i] - nums[j]| <= maxDiff).

You are also given a 2D integer array queries. For each queries[i] = [ui, vi], determine whether there exists a path between nodes ui and vi.

Return a boolean array answer, where answer[i] is true if there exists a path between ui and vi in the ith query and false otherwise.

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
vector<bool> pathExistenceQueries(int n, vector<int>& nums, int maxDiff, vector<vector<int>>& queries) {
vector<int> root(n);
for(int i = 1; i < n; i++) root[i] = nums[i] <= nums[i-1] + maxDiff ? root[i-1] : i;
vector<bool> res(queries.size());
for(int i = 0; i < queries.size(); i++) res[i] = root[queries[i][0]] == root[queries[i][1]];
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/04/27/PS/LeetCode/path-existence-queries-in-a-graph-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.