Untitled
unknown
plain_text
10 months ago
948 B
18
Indexable
function findMinimumLengthSubarray(arr, k) {
const n = arr.length;
if (k > n) return -1;
let freq = new Map();
let left = 0;
let distinct = 0;
let minLen = Infinity;
for (let right = 0; right < n; right++) {
// Add current element
freq.set(arr[right], (freq.get(arr[right]) || 0) + 1);
if (freq.get(arr[right]) === 1) distinct++;
// While window has at least k distinct, shrink from left
while (distinct >= k) {
minLen = Math.min(minLen, right - left + 1);
// Shrink left
freq.set(arr[left], freq.get(arr[left]) - 1);
if (freq.get(arr[left]) === 0) {
freq.delete(arr[left]);
distinct--;
}
left++;
}
}
return minLen === Infinity ? -1 : minLen;
}
// Example usage:
console.log(findMinimumLengthSubarray([2, 2, 1, 1, 3], 3));Editor is loading...
Leave a Comment