Skip to main content

Minimum Unique Shrink Window

hard
StringTwo PointersSliding WindowHash TableSliding WindowTwo Pointer Pair Sum
Asked atGoogleAmazonMetaUber

Problem Description

Given a string `text` and an integer `distinctGoal`, find the length of the shortest contiguous substring that contains **exactly** `distinctGoal` distinct characters. If no such substring exists, return `-1`.

**Example 1:**
```
Input: text = "aabcbcdb", distinctGoal = 3
Output: 3
Explanation: The substring "bcd" (indices 4-6) has exactly 3 distinct characters and length 3.
```

**Example 2:**
```
Input: text = "xyzzyx", distinctGoal = 2
Output: 2
Explanation: "xy" or "yz" or "zy" or "yx" each contain exactly 2 distinct characters with length 2.
```

Constraints

  • 1 <= text.length <= 10^5
  • 1 <= distinctGoal <= 26
  • text contains only lowercase English letters

Follow-up

Extend the solution to find the shortest substring containing exactly `distinctGoal` distinct characters each appearing at least twice.

Hints

Try the problem first. If you get stuck, you can reveal hints one at a time.

Solution

Leaderboard

No entries yet for python.

Be the first — submit an accepted solution.