function minUniqueSubarrayLength(arr) {
const N = arr.filter((v, i, a) => i === a.indexOf(v)).length;
let begin = 0;
let end = -1;
let uniques = {};
let uniqCount = 0;
let subLength = arr.length;
let len = 0;
while (true) {
if (uniqCount < N) {
end += 1;
len += 1;
if (end === arr.length) {
return subLength;
}
uniques[arr[end]] = (uniques[arr[end]] ?? 0) + 1;
if (uniques[arr[end]] === 1) {
uniqCount += 1;
}
continue;
}
if (subLength > len) {
subLength = len;
if (subLength === N) {
return subLength;
}
}
uniques[arr[begin]] -= 1;
if (uniques[arr[begin]] === 0) {
uniqCount -= 1;
}
begin += 1;
len -= 1;
}
}
console.log(minUniqueSubarrayLength([1,1,1,3,2,1,3,2,2,2,1])); // 3
console.log(minUniqueSubarrayLength([1,2,2,2,3,4,2,2,2])); // 6
console.log(minUniqueSubarrayLength([1,1,1,2,3,3,4,1,1,1,1,1,1,4,3,3,3,2,1,1,1,2])); // 5