Skip to content

1923. Longest Common Subpath 👍

  • Time: $O(mn \log n)$
  • Space: $O(mn)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Solution {
  public int longestCommonSubpath(int n, int[][] paths) {
    int l = 0;
    int r = paths[0].length;

    while (l < r) {
      final int m = l + (r - l + 1) / 2;
      if (checkCommonSubpath(paths, m))
        l = m;
      else
        r = m - 1;
    }

    return l;
  }

  private static final long kBase = 165_131L;
  private static final long kHash = 8_417_508_174_513L;

  // Returns true if there's a common subpath of length m for all the paths.
  private boolean checkCommonSubpath(int[][] paths, int m) {
    Set<Long>[] hashSets = new Set[paths.length];

    // Calculate the hash values for subpaths of length m for every path.
    for (int i = 0; i < paths.length; ++i)
      hashSets[i] = rabinKarp(paths[i], m);

    // Check if there is a common subpath of length m.
    for (final long subpathHash : hashSets[0])
      if (Arrays.stream(hashSets).allMatch(hashSet -> hashSet.contains(subpathHash)))
        return true;

    return false;
  }

  // Returns the hash values for subpaths of length m in the path.
  private Set<Long> rabinKarp(int[] path, int m) {
    Set<Long> hashes = new HashSet<>();
    long maxPower = 1;
    long hash = 0;
    for (int i = 0; i < path.length; ++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.add(hash);
    }
    return hashes;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution:
  def __init__(self):
    self.kBase = 165_131
    self.kHash = 8_417_508_174_513

  def longestCommonSubpath(self, n: int, paths: list[list[int]]) -> int:
    l = 0
    r = len(paths[0])

    while l < r:
      m = l + (r - l + 1) // 2
      if self._checkCommonSubpath(paths, m):
        l = m
      else:
        r = m - 1

    return l

  def _checkCommonSubpath(self, paths: list[list[int]], m: int) -> bool:
    """
    Returns True if there's a common subpath of length m for all the paths.
    """
    # Calculate the hash values for subpaths of length m for every path.
    hashSets = [self._rabinKarp(path, m) for path in paths]

    # Check if there is a common subpath of length m.
    for subpathHash in hashSets[0]:
      if all(subpathHash in hashSet for hashSet in hashSets):
        return True

    return False

  def _rabinKarp(self, path: list[int], m: int) -> set[int]:
    """Returns the hash values for subpaths of length m in the path."""
    hashes = set()
    maxPower = 1
    hash = 0

    for i, num in enumerate(path):
      hash = (hash * self.kBase + num) % self.kHash
      if i >= m:
        hash = (hash - path[i - m] * maxPower %
                self.kHash + self.kHash) % self.kHash
      else:
        maxPower = maxPower * self.kBase % self.kHash
      if i >= m - 1:
        hashes.add(hash)

    return hashes