VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-length-of-repeating-substring/

⇱ Find length of repeating Substring - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find length of repeating Substring

Last Updated : 14 Aug, 2023

Given a string s and a positive integer K, the task is to find the length of the longest contiguous substring that appears at least K times in s.

Examples:

Input: s = "abababcdabcd", K = 2
Output: 4
Explanation: "abcd" is the longest repeating substring at least K times.

Input: s = "aacd", K = 4
Output: 0

Approach: This can be solved with the following idea:

We will use the Rabin-Karp algorithm to solve this problem, which is a rolling hash-based algorithm to find the longest common substring that repeats at least k times.

Below are the steps: 

  • Initialize the parameters: base, modulus, and power.
  • Define a function for computing the rolling hash.
  • Define a function for binary search to find the largest substring length.
  • For each possible substring length, use the Rabin-Karp algorithm to check if it repeats at least K times.
  • Return the longest substring length that meets the requirement.

Below is the implementation of the above code:


Output
4

Time Complexity: O(N*log(N))
Auxiliary Space: O(N)

Comment
Article Tags: