/**
* Problem: LeetCode 3532 - Path Existence Queries in a Graph I
* Difficulty: Medium
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public boolean[] pathExistenceQueries(int n, int[] nums, int maxDiff, int[][] queries) {
int[] component = new int[n];
int id = 0;
component[0] = 0;
for (int i = 1; i < n; i++) {
if (nums[i] - nums[i - 1] > maxDiff) {
id++;
}
component[i] = id;
}
boolean[] ans = new boolean[queries.length];
for (int i = 0; i < queries.length; i++) {
ans[i] = component[queries[i][0]] == component[queries[i][1]];
}
return ans;
}
}
"""
Problem: LeetCode 3532 - Path Existence Queries in a Graph I
Difficulty: Medium
Language: Python
Author: CodeByTushu
"""
from typing import List
class Solution:
def pathExistenceQueries(self, n: int, nums: List[int], maxDiff: int, queries: List[List[int]]) -> List[bool]:
component = [0] * n
cid = 0
# Since nums is sorted, non-decreasing order guarantees that
# any gap > maxDiff splits elements into distinct connected components.
for i in range(1, n):
if nums[i] - nums[i - 1] > maxDiff:
cid += 1
component[i] = cid
return [component[u] == component[v] for u, v in queries]
/**
* Problem: LeetCode 3532 - Path Existence Queries in a Graph I
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
#include <vector>
using namespace std;
/**
* Problem: LeetCode 3532 - Path Existence Queries in a Graph I
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
class Solution {
public:
vector<bool> pathExistenceQueries(int n, vector<int>& nums, int maxDiff, vector<vector<int>>& queries) {
vector<int> component(n, 0);
int id = 0;
// nums is sorted in non-decreasing order.
// A difference > maxDiff creates a disconnected component boundary.
for (int i = 1; i < n; i++) {
if (nums[i] - nums[i - 1] > maxDiff) {
id++;
}
component[i] = id;
}
vector<bool> ans(queries.size());
for (size_t i = 0; i < queries.size(); i++) {
ans[i] = (component[queries[i][0]] == component[queries[i][1]]);
}
return ans;
}
};
/**
* Problem: LeetCode 3532 - Path Existence Queries in a Graph I
* Difficulty: Medium
* Language: JavaScript
* Author: CodeByTushu
*/
var pathExistenceQueries = function(n, nums, maxDiff, queries) {
const component = new Int32Array(n);
let id = 0;
// nums is sorted in non-decreasing order.
// Consecutive differences > maxDiff partition the nodes into separate components.
for (let i = 1; i < n; i++) {
if (nums[i] - nums[i - 1] > maxDiff) {
id++;
}
component[i] = id;
}
const ans = new Array(queries.length);
for (let i = 0; i < queries.length; i++) {
ans[i] = component[queries[i][0]] === component[queries[i][1]];
}
return ans;
};