- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 69 lines of C++ from the credited upstream file 3534.cpp.
- The implementation visibly relies on sequence storage.
- 8 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<int> pathExistenceQueries(int n, vector<int>& nums, int maxDiff,4 vector<vector<int>>& queries) {5 vector<int> ans;6 vector<int> sortedNums;7 vector<int> indexMap(n);8 vector<pair<int, int>> sortedNumAndIndexes;9 10 for (int i = 0; i < n; ++i)11 sortedNumAndIndexes.emplace_back(nums[i], i);12 13 ranges::sort(sortedNumAndIndexes);14 15 for (int i = 0; i < n; ++i) {16 const auto& [num, sortedIndex] = sortedNumAndIndexes[i];17 sortedNums.push_back(num);18 indexMap[sortedIndex] = i;19 }20 21 const int maxLevel = std::bit_width(static_cast<unsigned>(n)) + 1;22 23 vector<vector<int>> jump(n, vector<int>(maxLevel));24 25 int right = 0;26 for (int i = 0; i < n; ++i) {27 while (right + 1 < n && sortedNums[right + 1] - sortedNums[i] <= maxDiff)28 ++right;29 jump[i][0] = right;30 }31 32 for (int level = 1; level < maxLevel; ++level)33 for (int i = 0; i < n; ++i) {34 const int prevJump = jump[i][level - 1];35 jump[i][level] = jump[prevJump][level - 1];36 }37 38 for (const vector<int>& query : queries) {39 const int u = query[0];40 const int v = query[1];41 const int uIndex = indexMap[u];42 const int vIndex = indexMap[v];43 const int start = min(uIndex, vIndex);44 const int end = max(uIndex, vIndex);45 const int res = minJumps(jump, start, end, maxLevel - 1);46 ans.push_back(res == INT_MAX ? -1 : res);47 }48 49 return ans;50 }51 52 private:53 54 55 int minJumps(const vector<vector<int>>& jump, int start, int end, int level) {56 if (start == end)57 return 0;58 if (jump[start][0] >= end)59 return 1;60 if (jump[start][level] < end)61 return INT_MAX;62 int j = level;63 for (; j >= 0; --j)64 if (jump[start][j] < end)65 break;66 return (1 << j) + minJumps(jump, jump[start][j], end, j);67 }68};69