Longest repeating and non-overlapping substring
Medium Accuracy: 38.27% Submissions: 1196 Points: 4

Given a string S, find the longest repeating non-overlapping substring in it. In other words find 2 identical substrings of maximum length which do not overlap. If there exists more than one such substring return any of them. Print the longest non-overlapping substring. If no such substring exists print -1.

Note: Multiple Answers are possible but you have to print the substring which occurs atleat twice first.

For Example: "ablhiabohi". Here both "ab" and "hi" are possible answers. But you will have to return "ab" as because it repeats before "hi".

 

Example 1:

Input:
N = 13
S = "geeksforgeeks"
Output:
geeks
Explanation:
The string "geeks" is the longest Substring
of S which is repeating but not overlapping.

Example 2:

Input:
N = 8
S = "heyhheyi"
Output:
hey
Explanation:
The string "hey" is the longest Substring
of S which is repeating but not overlapping.

 

Your Task:
You don't need to read input or print anything. Your task is to complete the function longestSubstring() which takes a Integer N and a String S as input and returns the answer.

 

Expected Time Complexity: O(N2)
Expected Auxiliary Space: O(N2)

 

Constraints:
1 <= N <= 103

We are replacing the old Disqus forum with the new Discussions section given below.
Click here to view old Disqus comments.


to report an issue on this page.

Editorial

We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?

Yes

All Submissions

My Submissions:

Login to access your submissions.

Longest repeating and non-overlapping substring

Output Window