Problem Description
Given n cities and m friends where each friend travels through some cities forming a path, find the length of the longest contiguous sequence of cities (subpath) that appears in every friend's path. If there is no common subpath, return 0.
Key Insights
- Use binary search on the potential length of common subpaths.
- For a fixed candidate length L, use rolling hash to efficiently compute and compare all subpaths of length L in each friend’s path.
- Intersect the sets of hashes from all paths. If the intersection is non-empty, a common subpath of length L exists.
- Using polynomial rolling hash reduces the time needed to check for common subpaths.
- Since the total length of all paths is at most 10^5, the combination of binary search and rolling hash is efficient.
Space and Time Complexity
Time Complexity: O(total_length * log(min_path_length)) where total_length is the sum of the lengths of all paths. Space Complexity: O(total_length) for storing hash values and power arrays.
Solution
The solution applies a binary search over the possible subpath lengths. For each candidate length L:
- Compute the rolling hash values for every contiguous subpath of length L for each friend’s path.
- Store these hash values in a set.
- Intersect the sets from each friend. If at any candidate length L, the intersection is non-empty, then a common subpath of that length exists.
- Adjust the binary search range according to the presence/absence of a common subpath. The use of a rolling hash (with a proper base and modulus) allows quick computation of subpath hashes with O(1) sliding-window updates.