#1923
Hard Algorithms Longest common subpath
Array Binary Search Rolling Hash Suffix Array Hash Function
29.4% acceptance
Feb 25, 2026
511
39
There is a country of n cities numbered from 0 to n - 1. In this country, there is a road connecting every pair of cities.
There are m friends numbered from 0 to m - 1 who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an integer array that contains the visited cities in order. The path may contain a city more than once, but the same city will not be listed consecutively.
Given an integer n and a 2D integer array paths where paths[i] is an integer array representing the path of the ith friend, return the length of the longest common subpath that is shared by every friend's path, or 0 if there is no common subpath at all.
A subpath of a path is a contiguous sequence of cities within that path.
Solution
Rust
Time O(n²)
Space O(n)
use std::collections::HashSet;
impl Solution {
pub fn longest_common_subpath(_n: i32, paths: Vec<Vec<i32>>) -> i32 {
let min_len = paths.iter().map(|p| p.len()).min().unwrap();
if min_len == 0 {
return 0;
}
let (mut lo, mut hi) = (0usize, min_len);
while lo < hi {
let mid = lo + (hi - lo + 1) / 2;
if Self::check(&paths, mid) {
lo = mid;
} else {
hi = mid - 1;
}
}
lo as i32
}
fn check(paths: &[Vec<i32>], len: usize) -> bool {
if len == 0 {
return true;
}
// Use double hashing to avoid collisions
const MOD1: u64 = 1_000_000_007;
const MOD2: u64 = 998_244_353;
const BASE1: u64 = 100_003;
const BASE2: u64 = 100_019;
let mut common: Option<HashSet<(u64, u64)>> = None;
for path in paths {
if path.len() < len {
return false;
}
let mut set = HashSet::new();
let mut h1 = 0u64;
let mut h2 = 0u64;
let mut pow1 = 1u64;
let mut pow2 = 1u64;
for i in 0..len {
h1 = (h1 * BASE1 + path[i] as u64 + 1) % MOD1;
h2 = (h2 * BASE2 + path[i] as u64 + 1) % MOD2;
if i > 0 {
pow1 = pow1 * BASE1 % MOD1;
pow2 = pow2 * BASE2 % MOD2;
}
}
set.insert((h1, h2));
for i in len..path.len() {
h1 = (h1 + MOD1 - pow1 * (path[i - len] as u64 + 1) % MOD1) % MOD1;
h1 = (h1 * BASE1 + path[i] as u64 + 1) % MOD1;
h2 = (h2 + MOD2 - pow2 * (path[i - len] as u64 + 1) % MOD2) % MOD2;
h2 = (h2 * BASE2 + path[i] as u64 + 1) % MOD2;
set.insert((h1, h2));
}
common = Some(match common {
None => set,
Some(prev) => prev.intersection(&set).copied().collect(),
});
if common.as_ref().unwrap().is_empty() {
return false;
}
}
!common.unwrap().is_empty()
}
}