KatInterview

Find Minimum Window Containing All Distinct Characters

Arrays & HashingAuto-graded · 18 test cases
MediumAuto-gradedArrays & Hashingsliding windowhash mapstrings

Last updated

Tests ability to use a sliding window combined with hash counting to find the shortest substring that contains every distinct character appearing in the input string.

Minimum Window With All Distinct Characters

Given a string s, find the length of the shortest contiguous substring (window) that contains every distinct character that appears anywhere in s, with each such character appearing at least once in the window.

Formally, let D be the set of all distinct characters in s. Find the minimum length of any substring of s that contains every character in D at least once.

Because every character in D comes from s itself, a valid window always exists (the whole string is always a valid window).

Tie-breaking / uniqueness: return the integer length only; the position of the window does not matter.

Constraints

  • 1 <= len(s) <= 2000
  • s consists of lowercase English letters only ('a'–'z').
  • The answer is always at least len(D) (the number of distinct characters in s).
  • If s has only one distinct character (e.g. "aaaa"), the answer is 1.

Examples

Example 1

Input: min_window_all_distinct('aabcbcdbca')

Output: 4

Example 2

Input: min_window_all_distinct('aaaa')

Output: 1

Example 3

Input: min_window_all_distinct('abcde')

Output: 5

Hints

Hint 1

Count how many distinct characters exist in s — that is your target; you need a window that satisfies all of them.

Hint 2

Use two pointers (left and right). Expand right to include new characters; once all distinct characters are covered, try shrinking from the left to minimize the window length.

Hint 3

Track a hash map of character counts inside the current window and a counter of how many distinct characters are currently 'satisfied' (count >= 1). Update the counter as you move the pointers.