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
the shortest segment containing all these characters starts at p_i and ends at p_{i+k-1}. Therefore, its length is determined as
Thus, the answer is
The overall time complexity is — .