Skip to main content

Minimum Length Subarray Covering All Targets

hard
ArrayTwo PointersHash TableSliding WindowSliding Window
Asked atAmazonGoogleMicrosoftMetaBloombergUberLinkedin

Problem Description

You are given an integer array `values` and a **non-empty** integer array `targets`.

Return the **minimum length** of a contiguous subarray of `values` that contains every integer in `targets` at least as many times as it appears in `targets`. If no such subarray exists, return `0`.

**Example 1:**
```
Input: values = [2, 6, 3, 4, 3, 6, 2, 1, 3], targets = [3, 6, 3]
Output: 4
Explanation: The subarray [3, 4, 3, 6] (indices 2..5) contains two 3s and one 6, matching targets.
```

**Example 2:**
```
Input: values = [1, 5, 2, 8, 5, 3], targets = [5, 5]
Output: 4
Explanation: The subarray [5, 2, 8, 5] (indices 1..4) is the shortest window containing two 5s.
```

Constraints

  • 1 <= values.length <= 10^5
  • 1 <= targets.length <= 10^5
  • 1 <= values[i], targets[i] <= 10^5

Follow-up

Return the actual subarray (start and end indices) instead of just its length.

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.