#P5341. Find the Most Frequent Substring Length with Exact $k$ Occurrences

    ID: 18574 Type: Default 1000ms 256MiB

Find the Most Frequent Substring Length with Exact $k$ Occurrences

Find the Most Frequent Substring Length with Exact kk Occurrences

You are given a string of length $n$ and an integer $k$. A substring is any contiguous subsequence of the string. Your task is to consider all distinct substrings that appear exactly $k$ times in the string. Group these substrings by their length, and then find the length for which the number of substrings is maximized. In case there are multiple lengths with the same maximum number of substrings, output the longest length among them.

If no substring appears exactly $k$ times, output -1.

Note: A substring of the string S is defined as S[i..j] for some valid indices.

Input format:

  • The first line contains two integers $n$ and $k$.
  • The second line contains the string of length $n$.

Output format: Output a single integer representing the substring length chosen by the method described above.

Example:
For the input:

4 2
abab
The distinct substrings of "abab" are: "a", "b", "ab", "ba", "aba", "bab", "abab". Among these, the ones that appear exactly $2$ times are "a" (length 1), "b" (length 1) and "ab" (length 2). Grouping by length gives:
Length 1: 2 substrings
Length 2: 1 substring
Thus, the answer is 1.

inputFormat

The first line of input contains two integers $n$ and $k$, where $n$ is the length of the string and $k$ is the frequency to match exactly.

The second line contains the string of length $n$.

outputFormat

Output a single integer: the length (of the substrings which appear exactly $k$ times) that belongs to the group with the maximum count. In case of a tie, choose the longest length. If no substring appears exactly $k$ times, output -1.

sample

4 2
abab
1