Approach
This is a really interseting problem that I have not seen before, we can leverage the “binary lifting” to do efficient searching.
It is clear that we can sort the nums first, and when two values are reachable, we always walk to the farest node. For instance when we have 2,4,6,8, and max step is 3, we can only jump from 2->4->6->8 with 3 steps. For 2,4,6,8 with step 5, we can jump 2->6 since it is the maximum reachable node. I find that the maximum reachable tree can be construct in O(N) with two pointer teachqniue, but I did not figure out what is the best way to query from the tree. I was thinking that in the worse case, we would need to jump N times, and for q queriues, we would need O(qN).
The interesting part is that we can do binary lifting! That is prestored the step to jump in 2^i times. Take the above example, we know that in one step the maximum jumping node array is 1,2,3,-1 (-1 denotes that it cannot jump to any node), and lets denote this as up[0]. We can then construct up[1][j] = up[0][up[0][j]], which means that we do two steps hopping. And for up[2][j] = up[1][up[1][j]], we do 4 steps hopping. Prebuild this takes O(NlgN) time, and each query is O(lgN), and total query time in O(qlgN).
Code
class Solution {
public:
vector<int> pathExistenceQueries(int n, vector<int>& nums, int maxDiff, vector<vector<int>>& queries) {
vector<pair<int, int>> v; // num, idx
for(int i = 0 ; i < n ; ++i) v.push_back({nums[i], i});
sort(v.begin(), v.end());
vector<int> parent(n);
int r = 0;
for(int l = 0 ; l < n ; ++l) {
while(r <= n - 1 && v[r].first <= v[l].first + maxDiff) ++r;
--r;
if(l == r) parent[l] = -1;
else parent[l] = r;
}
vector<int> pos(n); // pointing to actual location
for(int i = 0 ; i < n ; ++i) {
pos[v[i].second] = i; // pos[originalIdx] = currentIdx;
}
int k = 0;
while ((1 << k) <= n) {
++k;
}
vector<vector<int>> up(k, vector<int>(n, -1));
up[0] = parent; // jump 1 time
for(int i = 1 ; i < k ; ++i) {
for(int j = 0 ; j < n ; ++j) {
if(up[i-1][j] == -1) up[i][j] = -1;
else up[i][j] = up[i-1][up[i-1][j]]; // jump 2^i times
}
}
vector<int> ans;
for(const auto& q: queries) {
int u = pos[q[0]];
int v = pos[q[1]];
if(u > v) swap(u, v);
int totalStep = 0;
for(int i = k-1 ; i >= 0 ; --i) {
if(u == v) break;
if(up[i][u] == -1) continue;
if(up[i][u] > v) continue;
totalStep += (1 << i);
u = up[i][u];
}
if(u != v && up[0][u] != -1) ans.push_back(totalStep+1);
else if(u != v && up[0][u] == -1) ans.push_back(-1);
else ans.push_back(totalStep);
}
return ans;
}
};