Minimum Substring Length#12781

Minimum Substring Length (Editorial)

Problem author:

Maryan Shyika

Prepared by:

Maryan Shyika

Tutorial:

Maryan Shyika

Idea

Let us write the positions of all G characters in the string into a separate array . Let the number of such positions be . Since we write the positions from left to right, the array is already sorted.

We need to choose characters G that are contained in the shortest possible segment. In the optimal answer, these characters will be consecutive in the array . Therefore, it is sufficient to iterate over all groups of consecutive elements.

For a group

p_i,p_{i+1},\ldots,p_{i+k-1}

the shortest segment containing all these characters starts at p_i and ends at p_{i+k-1}. Therefore, its length is determined as

p_{i+k-1}-p_i.

Thus, the answer is

\min_{1 \le i \le m-k+1}(p_{i+k-1}-p_i).

The overall time complexity is — .