Problem solution · C++

Longest Common Subpath

Longest Common Subpath: a C++ solution using sliding window or two pointers. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Sliding window or two pointers
Source
walkccc LeetCode Solutions
Length
57 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

Sliding window or two pointers

For Longest Common Subpath, the implementation maintains a moving interval and updates only the information that enters or leaves the window.

  1. Choose the invariant that makes a window valid or useful.
  2. Advance the right boundary and add the new element.
  3. Move the left boundary only as needed while maintaining the invariant and updating the answer.

Code notes

  • 57 lines of C++ from the credited upstream file 1923.cpp.
  • The implementation visibly relies on sequence storage, hash lookup.
  • 4 loop blocks detected.

Complexity

Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.

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 codeLongest Common Subpath · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  int longestCommonSubpath(int n, vector<vector<int>>& paths) {    int l = 0;    int r = paths[0].size();     while (l < r) {      const int m = l + (r - l + 1) / 2;      if (checkCommonSubpath(paths, m))        l = m;      else        r = m - 1;    }     return l;  }   static constexpr long kBase = 165'131;  static constexpr long kHash = 8'417'508'174'513;   // Returns true if there's a common subpath of length m for all the paths.  bool checkCommonSubpath(const vector<vector<int>>& paths, int m) {    vector<unordered_set<long>> hashSets;     // Calculate the hash values for subpaths of length m for every path.    for (const vector<int>& path : paths)      hashSets.push_back(rabinKarp(path, m));     // Check if there is a common subpath of length m.    for (const long subpathHash : hashSets[0])      if (ranges::all_of(hashSets,                         [subpathHash](const unordered_set<long>& hashSet) {        return hashSet.contains(subpathHash);      }))        return true;     return false;  }   // Returns the hash values for subpaths of length m in the path.  unordered_set<long> rabinKarp(const vector<int>& path, int m) {    unordered_set<long> hashes;    long maxPower = 1;    long hash = 0;    for (int i = 0; i < path.size(); ++i) {      hash = (hash * kBase + path[i]) % kHash;      if (i >= m)        hash = (hash - path[i - m] * maxPower % kHash + kHash) % kHash;      else        maxPower = maxPower * kBase % kHash;      if (i >= m - 1)        hashes.insert(hash);    }    return hashes;  }}; 

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 ↗