Problem solution · C++

Path Existence Queries in a Graph II

Path Existence Queries in a Graph II: a C++ solution using binary search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Binary search
Source
walkccc LeetCode Solutions
Length
69 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Binary search

For Path Existence Queries in a Graph II, the implementation exploits a monotonic condition to discard half of the remaining search space after every check.

  1. Identify the ordered answer range or sorted search domain.
  2. Write a predicate whose truth changes only once.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codePath Existence Queries in a Graph II · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  vector<int> pathExistenceQueries(int n, vector<int>& nums, int maxDiff,                                   vector<vector<int>>& queries) {    vector<int> ans;    vector<int> sortedNums;    vector<int> indexMap(n);    vector<pair<int, int>> sortedNumAndIndexes;     for (int i = 0; i < n; ++i)      sortedNumAndIndexes.emplace_back(nums[i], i);     ranges::sort(sortedNumAndIndexes);     for (int i = 0; i < n; ++i) {      const auto& [num, sortedIndex] = sortedNumAndIndexes[i];      sortedNums.push_back(num);      indexMap[sortedIndex] = i;    }     const int maxLevel = std::bit_width(static_cast<unsigned>(n)) + 1;    // jump[i][j] := the index of the j-th ancestor of i    vector<vector<int>> jump(n, vector<int>(maxLevel));     int right = 0;    for (int i = 0; i < n; ++i) {      while (right + 1 < n && sortedNums[right + 1] - sortedNums[i] <= maxDiff)        ++right;      jump[i][0] = right;    }     for (int level = 1; level < maxLevel; ++level)      for (int i = 0; i < n; ++i) {        const int prevJump = jump[i][level - 1];        jump[i][level] = jump[prevJump][level - 1];      }     for (const vector<int>& query : queries) {      const int u = query[0];      const int v = query[1];      const int uIndex = indexMap[u];      const int vIndex = indexMap[v];      const int start = min(uIndex, vIndex);      const int end = max(uIndex, vIndex);      const int res = minJumps(jump, start, end, maxLevel - 1);      ans.push_back(res == INT_MAX ? -1 : res);    }     return ans;  }  private:  // Returns the minimum number of jumps from `start` to `end` using binary  // lifting.  int minJumps(const vector<vector<int>>& jump, int start, int end, int level) {    if (start == end)      return 0;    if (jump[start][0] >= end)      return 1;    if (jump[start][level] < end)      return INT_MAX;    int j = level;    for (; j >= 0; --j)      if (jump[start][j] < end)        break;    return (1 << j) + minJumps(jump, jump[start][j], end, j);  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗