1276. Shortest Letter Quota

Easy1.5 points estimatedSliding WindowStringTwo Pointers

A proofreader scans a line of lowercase text s looking for a short passage that is rich in one particular character. Given the character letter and a quota k, find the shortest contiguous substring of s that contains letter at least k times, and return its length.

If letter appears fewer than k times in the whole string, return -1. Record the position of every occurrence of letter; any optimal substring starts and ends on an occurrence, so compare each group of k consecutive occurrences by the span between the first and the last of them. Aim for O(n) time and O(n) extra space, or O(1) with a sliding window.

Example 1

Input:
s = "abcabcabc", letter = "b", k = 2
Output:
4
Explanation:

The letter b sits at positions 1, 4 and 7, so the shortest span holding two of them is positions 1 to 4, length 4.

Example 2

Input:
s = "xyz", letter = "a", k = 1
Output:
-1
Explanation:

The letter a never occurs, so the answer is -1.

Constraints

1 ≤ s.length ≤ 1000

1 ≤ k ≤ s.length

s and letter are lowercase English letters

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(n)

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…