#K72592. Smallest Alphabet Word Substring
Smallest Alphabet Word Substring
Smallest Alphabet Word Substring
You are given a string s
consisting of lowercase English letters. An alphabet word is defined as a string that contains all the letters from a to z at least once. Your task is to find the length of the smallest contiguous substring of s
that is an alphabet word.
If no such substring exists, output -1
.
The solution requires a sliding window technique with an average time complexity of O(n), where n is the length of the input string. The essence of the solution is to maintain a window that expands and contracts so that all 26 letters are included. Algebraically, if the current window is defined by indices l and r, then the minimum substring length can be formulated as:
[ minLength = \min_{l \leq r \leq n} {r-l+1 ; | ; {s[l], s[l+1],\dots,s[r]} \supseteq {a, b, \dots, z}} ]
If such a window cannot be found, return -1
.
inputFormat
The input is read from stdin as a single string s
(which may contain spaces and newline characters). For this problem, you can assume that the string only contains lowercase English letters ('a'-'z').
outputFormat
Output the length of the smallest substring of s
that contains every letter from 'a' to 'z' at least once. If no such substring exists, output -1
. The output should be printed to stdout as a single integer.
abcdefghijklmnopqrstuvwxyzabc
26