Unique Longest Common Substring

Moderate
0/80
0 upvote
Asked in company
Frugal Testing

Problem statement

You are given two strings, s1 and s2, consisting of lowercase English letters. Your task is to find the length of the longest "unique common substring".

A substring sub is considered a unique common substring if it satisfies all of the following conditions:

1) sub is a substring of s1.


2) sub is a substring of s2.


3) sub appears exactly once within s1.


4) sub appears exactly once within s2.


If no such substring exists, the answer is 0.


Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains the string s1.
The second line of input contains the string s2.


Output Format:
Print a single integer representing the length of the longest unique common substring.


Note:
A substring is a contiguous block of characters. For example, "app" is a substring of "apple", but "ale" is not.
Sample Input 1:
abcy
zbcd


Sample Output 1:
2


Explanation for Sample 1:
The common substrings are "b", "c", and "bc".
- "b": Appears once in `s1` and once in `s2`. It is a valid unique common substring of length 1.
- "c": Appears once in `s1` and once in `s2`. It is a valid unique common substring of length 1.
- "bc": Appears once in `s1` and once in `s2`. It is a valid unique common substring of length 2.
The longest among these has a length of 2.


Sample Input 2:
ababa
abac


Sample Output 2:
0


Explanation for Sample 2:
The longest common substring is "aba".
- "aba": Appears twice in `s1` ("ababa") and once in `s2`. Since it repeats in `s1`, it is not a *unique* common substring.
The next longest common substring is "ab".
- "ab": Appears twice in `s1` ("ababa") and once in `s2`. It also repeats in `s1`, so it is not valid.
No common substring satisfies the uniqueness criteria for both strings. Therefore, the answer is 0.


Expected Time Complexity:
A direct approach has a time complexity around O(N*M*min(N,M)), where N and M are the lengths of the strings.


Constraints:
1 <= N, M <= 1000
`s1` and `s2` consist of lowercase English letters.

Time limit: 1 sec
Approaches (1)
Unique Longest Common Substring
Time Complexity
Space Complexity
Code Solution
(100% EXP penalty)
Unique Longest Common Substring
Full screen
Console