FastPrepShortest Substring with at Least K Distinct Characters

Shortest Substring with at Least K Distinct Characters

Navan logoNavan● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Return the minimum length of a contiguous substring of text that contains at least k distinct characters. Return -1 if no such substring exists.

Function

shortestAtLeastKDistinct(text: String, k: int) → int

Examples

Example 1

text = "aabcbcdbca"k = 3return = 3

The substring abc has three distinct characters.

Example 2

text = "aaaa"k = 2return = -1

Only one distinct character exists.

Constraints

  • 1 <= text.length <= 200000.
  • 1 <= k <= 256.
  • For this exercise, assume text contains only ASCII characters; one character is one byte.

More Navan problems

See Navan hiring insights
public int shortestAtLeastKDistinct(String text, int k) {
    // Write your code here.
}
text"aabcbcdbca"
k3
expected3
Checking account…