#1923

Longest Common Subpath

Hard
ArrayBinary SearchRolling HashSuffix ArrayHash FunctionHash MapBinary SearchRolling Hash
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log m)
Space
O(1)
O(n)
💡

Intuition

Time O(n log m)Space O(n)

We can use binary search to find the maximum length of the common subpath and a rolling hash to efficiently check for common subpaths in all paths.

⚙️

Algorithm

3 steps
  1. 1Step 1: Define a function to check if there is a common subpath of a given length using rolling hash.
  2. 2Step 2: Use binary search on the length of the subpath from 0 to the length of the shortest path.
  3. 3Step 3: For each mid value in binary search, check if there is a common subpath of that length.
solution.py23 lines
1def longestCommonSubpath(n, paths):
2    def check_length(length):
3        seen = set()
4        base = 10**5 + 7
5        mod = 2**63 - 1
6        for path in paths:
7            current_hash = 0
8            for i in range(length):
9                current_hash = (current_hash * base + path[i]) % mod
10            seen.add(current_hash)
11            for i in range(length, len(path)):
12                current_hash = (current_hash * base - path[i - length] * (base ** length) % mod + path[i]) % mod
13                seen.add(current_hash)
14        return len(seen) > 1
15
16    left, right = 0, min(len(path) for path in paths)
17    while left < right:
18        mid = (left + right + 1) // 2
19        if check_length(mid):
20            left = mid
21        else:
22            right = mid - 1
23    return left

Complexity note: The time complexity is O(n log m) due to binary search over the length of the subpath and checking each length using rolling hash, where m is the number of paths.

  • 1Using binary search reduces the number of checks needed to find the longest common subpath.
  • 2Rolling hash allows for efficient substring comparison, avoiding the need for nested loops.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.