KatInterview

Longest Window Where Every Letter Meets a Minimum Count

StringsAuto-graded · 24 test cases
MediumAuto-gradedStringssliding-windowstringshash-map

Last updated

Find the longest contiguous substring in which every letter that appears occurs at least k times, using a sliding window or divide and conquer.

Longest Window Where Every Letter Meets a Minimum Count

You are given a string s made of lowercase English letters and an integer k.

A substring is a contiguous block of characters of s. Call a substring k-dense if every distinct letter that appears in it occurs at least k times inside that substring.

Return the length of the longest k-dense substring of s. If there is none, return -1.

Rules and edge cases

  • If k <= 1, return len(s). This applies even when s is empty, in which case the result is 0.
  • If k >= 2 and s is empty, return -1.
  • If k > len(s), return -1.
  • Otherwise, return the length of the longest k-dense non-empty substring, or -1 if no non-empty substring qualifies.
  • Only the length is returned, so ties between substrings do not matter.

Constraints

  • s contains only characters 'a' to 'z'.
  • 0 <= len(s) <= 10^5
  • k is an integer and may be zero or negative. Such values follow the k <= 1 rule above.
  • The expected running time is roughly linear in len(s) (up to a factor of 26).

Examples

Example 1

Input: longest_dense_window('aaabb', 3)

Output: 3

Example 2

Input: longest_dense_window('ababbc', 2)

Output: 5

Example 3

Input: longest_dense_window('abcdef', 2)

Output: -1

Example 4

Input: longest_dense_window('a', 1)

Output: 1

Hints

Hint 1

Think about what makes a substring invalid: any letter that appears fewer than k times in the whole string can never be part of a k-dense substring, so it acts as a separator.

Hint 2

Divide and conquer: count the letters, split the string at every letter whose total count is below k, and recurse on the pieces. If no letter is below k, the whole piece is valid.

Hint 3

Alternative: for each target number of distinct letters t from 1 to 26, run a sliding window that keeps at most t distinct letters and tracks how many of them have reached count k. Record the window length when both numbers equal t.