1288. Shortest Variety Window

A radio operator scans a stream of coded letters and wants the quickest burst that uses enough different symbols. Given a string s of lowercase letters and an integer k, return the length of the shortest contiguous substring of s that contains at least k different letters. If s has fewer than k different letters in total, return -1. Only the length is returned, so it does not matter which of several equally short substrings is chosen.

Aim for O(n) time and O(1) extra space, where n is the length of s: for each right end, shrink from the left while the window still holds at least k different letters, tracking counts in a 26-entry array.

Example 1

Input:
s = "abcab", k = 3
Output:
3
Explanation:

The substring 'abc' at the start has three different letters and no shorter substring does, so the answer is 3.

Example 2

Input:
s = "aaabb", k = 2
Output:
2
Explanation:

The substring 'ab' around the middle already holds two different letters, and a single letter does not, so the answer is 2.

Example 3

Input:
s = "aaa", k = 2
Output:
-1
Explanation:

The string has only one distinct letter, so two different letters never appear and the answer is -1.

Constraints

1 ≤ s.length ≤ 2 * 105

1 ≤ k ≤ 26

s consists of lowercase letters

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…