Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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.
Example 1:
Input: n = 5, paths = [[0,1,2,3,4],
[2,3,4],
[4,0,1,2,3]]
Output: 2
Explanation: The longest common subpath is [2,3].
Example 2:
Input: n = 3, paths = [[0],[1],[2]] Output: 0 Explanation: There is no common subpath shared by the three paths.
Example 3:
Input: n = 5, paths = [[0,1,2,3,4],
[4,3,2,1,0]]
Output: 1
Explanation: The possible longest common subpaths are [0], [1], [2], [3], and [4]. All have a length of 1.
Constraints:
1 <= n <= 105m == paths.length2 <= m <= 105sum(paths[i].length) <= 1050 <= paths[i][j] < npaths[i].Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Binary Search
5 [[0,1,2,3,4],[2,3,4],[4,0,1,2,3]]
3 [[0],[1],[2]]
5 [[0,1,2,3,4],[4,3,2,1,0]]
reconstruct-itinerary)maximum-length-of-repeated-subarray)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1923: Longest Common Subpath
class Solution {
int N = 100010;
long[] h = new long[N];
long[] p = new long[N];
private int[][] paths;
Map<Long, Integer> cnt = new HashMap<>();
Map<Long, Integer> inner = new HashMap<>();
public int longestCommonSubpath(int n, int[][] paths) {
int left = 0, right = N;
for (int[] path : paths) {
right = Math.min(right, path.length);
}
this.paths = paths;
while (left < right) {
int mid = (left + right + 1) >> 1;
if (check(mid)) {
left = mid;
} else {
right = mid - 1;
}
}
return left;
}
private boolean check(int mid) {
cnt.clear();
inner.clear();
p[0] = 1;
for (int j = 0; j < paths.length; ++j) {
int n = paths[j].length;
for (int i = 1; i <= n; ++i) {
p[i] = p[i - 1] * 133331;
h[i] = h[i - 1] * 133331 + paths[j][i - 1];
}
for (int i = mid; i <= n; ++i) {
long val = get(i - mid + 1, i);
if (!inner.containsKey(val) || inner.get(val) != j) {
inner.put(val, j);
cnt.put(val, cnt.getOrDefault(val, 0) + 1);
}
}
}
int max = 0;
for (int val : cnt.values()) {
max = Math.max(max, val);
}
return max == paths.length;
}
private long get(int l, int r) {
return h[r] - h[l - 1] * p[r - l + 1];
}
}
// Accepted solution for LeetCode #1923: Longest Common Subpath
// Auto-generated Go example from java.
func exampleSolution() {
}
// Reference (java):
// // Accepted solution for LeetCode #1923: Longest Common Subpath
// class Solution {
// int N = 100010;
// long[] h = new long[N];
// long[] p = new long[N];
// private int[][] paths;
// Map<Long, Integer> cnt = new HashMap<>();
// Map<Long, Integer> inner = new HashMap<>();
//
// public int longestCommonSubpath(int n, int[][] paths) {
// int left = 0, right = N;
// for (int[] path : paths) {
// right = Math.min(right, path.length);
// }
// this.paths = paths;
// while (left < right) {
// int mid = (left + right + 1) >> 1;
// if (check(mid)) {
// left = mid;
// } else {
// right = mid - 1;
// }
// }
// return left;
// }
//
// private boolean check(int mid) {
// cnt.clear();
// inner.clear();
// p[0] = 1;
// for (int j = 0; j < paths.length; ++j) {
// int n = paths[j].length;
// for (int i = 1; i <= n; ++i) {
// p[i] = p[i - 1] * 133331;
// h[i] = h[i - 1] * 133331 + paths[j][i - 1];
// }
// for (int i = mid; i <= n; ++i) {
// long val = get(i - mid + 1, i);
// if (!inner.containsKey(val) || inner.get(val) != j) {
// inner.put(val, j);
// cnt.put(val, cnt.getOrDefault(val, 0) + 1);
// }
// }
// }
// int max = 0;
// for (int val : cnt.values()) {
// max = Math.max(max, val);
// }
// return max == paths.length;
// }
//
// private long get(int l, int r) {
// return h[r] - h[l - 1] * p[r - l + 1];
// }
// }
# Accepted solution for LeetCode #1923: Longest Common Subpath
class Solution:
def longestCommonSubpath(self, n: int, paths: List[List[int]]) -> int:
def check(k: int) -> bool:
cnt = Counter()
for h in hh:
vis = set()
for i in range(1, len(h) - k + 1):
j = i + k - 1
x = (h[j] - h[i - 1] * p[j - i + 1]) % mod
if x not in vis:
vis.add(x)
cnt[x] += 1
return max(cnt.values()) == m
m = len(paths)
mx = max(len(path) for path in paths)
base = 133331
mod = 2**64 + 1
p = [0] * (mx + 1)
p[0] = 1
for i in range(1, len(p)):
p[i] = p[i - 1] * base % mod
hh = []
for path in paths:
k = len(path)
h = [0] * (k + 1)
for i, x in enumerate(path, 1):
h[i] = h[i - 1] * base % mod + x
hh.append(h)
l, r = 0, min(len(path) for path in paths)
while l < r:
mid = (l + r + 1) >> 1
if check(mid):
l = mid
else:
r = mid - 1
return l
// Accepted solution for LeetCode #1923: Longest Common Subpath
/**
* [1923] Longest Common Subpath
*
* 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 i^th 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.
*
* Example 1:
*
* Input: n = 5, paths = [[0,1,<u>2,3</u>,4],
* [<u>2,3</u>,4],
* [4,0,1,<u>2,3</u>]]
* Output: 2
* Explanation: The longest common subpath is [2,3].
*
* Example 2:
*
* Input: n = 3, paths = [[0],[1],[2]]
* Output: 0
* Explanation: There is no common subpath shared by the three paths.
*
* Example 3:
*
* Input: n = 5, paths = [[<u>0</u>,1,2,3,4],
* [4,3,2,1,<u>0</u>]]
* Output: 1
* Explanation: The possible longest common subpaths are [0], [1], [2], [3], and [4]. All have a length of 1.
*
* Constraints:
*
* 1 <= n <= 10^5
* m == paths.length
* 2 <= m <= 10^5
* sum(paths[i].length) <= 10^5
* 0 <= paths[i][j] < n
* The same city is not listed multiple times consecutively in paths[i].
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/longest-common-subpath/
// discuss: https://leetcode.com/problems/longest-common-subpath/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn longest_common_subpath(n: i32, paths: Vec<Vec<i32>>) -> i32 {
0
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_1923_example_1() {
let n = 5;
let paths = vec![vec![0, 1, 2, 3, 4], vec![2, 3, 4], vec![4, 0, 1, 2, 3]];
let result = 2;
assert_eq!(Solution::longest_common_subpath(n, paths), result);
}
#[test]
#[ignore]
fn test_1923_example_2() {
let n = 3;
let paths = vec![vec![0], vec![1], vec![2]];
let result = 0;
assert_eq!(Solution::longest_common_subpath(n, paths), result);
}
#[test]
#[ignore]
fn test_1923_example_3() {
let n = 5;
let paths = vec![vec![0, 1, 2, 3, 4], vec![4, 3, 2, 1]];
let result = 1;
assert_eq!(Solution::longest_common_subpath(n, paths), result);
}
}
// Accepted solution for LeetCode #1923: Longest Common Subpath
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1923: Longest Common Subpath
// class Solution {
// int N = 100010;
// long[] h = new long[N];
// long[] p = new long[N];
// private int[][] paths;
// Map<Long, Integer> cnt = new HashMap<>();
// Map<Long, Integer> inner = new HashMap<>();
//
// public int longestCommonSubpath(int n, int[][] paths) {
// int left = 0, right = N;
// for (int[] path : paths) {
// right = Math.min(right, path.length);
// }
// this.paths = paths;
// while (left < right) {
// int mid = (left + right + 1) >> 1;
// if (check(mid)) {
// left = mid;
// } else {
// right = mid - 1;
// }
// }
// return left;
// }
//
// private boolean check(int mid) {
// cnt.clear();
// inner.clear();
// p[0] = 1;
// for (int j = 0; j < paths.length; ++j) {
// int n = paths[j].length;
// for (int i = 1; i <= n; ++i) {
// p[i] = p[i - 1] * 133331;
// h[i] = h[i - 1] * 133331 + paths[j][i - 1];
// }
// for (int i = mid; i <= n; ++i) {
// long val = get(i - mid + 1, i);
// if (!inner.containsKey(val) || inner.get(val) != j) {
// inner.put(val, j);
// cnt.put(val, cnt.getOrDefault(val, 0) + 1);
// }
// }
// }
// int max = 0;
// for (int val : cnt.values()) {
// max = Math.max(max, val);
// }
// return max == paths.length;
// }
//
// private long get(int l, int r) {
// return h[r] - h[l - 1] * p[r - l + 1];
// }
// }
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.