Longest Common Subpath - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: n = 5, paths = [[0,1,2,3,4],[2,3,4],[4,0,3,2,1,5]]
Output: 2
💡 Note: The longest common subpath is [2,3] with length 2. It appears in paths[0] as [2,3], in paths[1] as [2,3], and in paths[2] as [3,2] (which contains [2,3] when read in different direction, but we need exact match). Actually, [4] appears in all three paths: paths[0][4], paths[1][2], and paths[2][0]. But [2,3] appears in paths[0][1:3] and paths[1][0:2]. Let's check [3,2]: appears in paths[2][2:4]. So common subpath [3,2] of length 2 exists.
Example 2 — No Common Subpath
$ Input: n = 3, paths = [[0,1,2],[1,2,0],[2,0,1]]
Output: 0
💡 Note: No subpath of length > 0 appears in all three paths due to different orderings
Example 3 — Single City Common
$ Input: n = 4, paths = [[0,1,2],[2,3],[1,2,3]]
Output: 1
💡 Note: City 2 appears in all paths: paths[0][2], paths[1][0], paths[2][1]. So longest common subpath has length 1.

Constraints

  • 1 ≤ n ≤ 105
  • 1 ≤ m ≤ 103
  • 1 ≤ paths[i].length ≤ 105
  • 0 ≤ paths[i][j] < n
  • All paths[i] are distinct

Visualization

Tap to expand
Longest Common Subpath: Find Shared Route SegmentsFind the longest contiguous sequence of cities that ALL friends visitedFriend 0: [0,1,2,3,4]Friend 1: [2,3,4]Friend 2: [4,0,3,2,1,5]Common Subpaths:Length 1: [2], [3], [4]Length 2: [2,3], [3,4]Length 3: None✓ [2,3] appears in all paths✓ [3,4] appears in all pathsOutput: 2 (maximum length)
Understanding the Visualization
1
Input Paths
Multiple friends each have a path through cities
2
Find Common Subpaths
Look for contiguous sequences that appear in all paths
3
Return Max Length
Output the length of the longest common subpath found
Key Takeaway
🎯 Key Insight: Binary search on length + rolling hash enables efficient subpath matching across all friend paths
Asked in
Google 15 Facebook 8 Amazon 5
8.2K Views
Medium Frequency
~45 min Avg. Time
267 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen