Description
Smallest Unique Subarray
HardYou are given an integer array nums.
Find the minimum length of a subarray that is not identical to any other subarray in nums.
Return an integer denoting the minimum possible length of such a subarray.
Two subarrays are considered identical if they have the same length and the same elements in corresponding positions.
Example 1:
Input: nums = [3,3,3]
Output: 3
Explanation:
- Subarrays of length 1:
[3]→ appears 3 times - Subarrays of length 2:
[3, 3]→ appears 2 times - Subarrays of length 3:
[3, 3, 3]→ appears once
The subarray [3, 3, 3] is unique, so the smallest unique subarray length is 3.
Example 2:
Input: nums = [2,1,2,3,3]
Output: 1
Explanation:
Subarrays of length 1:
[2]→ appears 2 times[1]→ appears once[3]→ appears 2 times
[1] is unique, so the smallest unique subarray length is 1.Example 3:
Input: nums = [1,1,2,2,1]
Output: 2
Explanation:
Subarrays of length 1:
[1]→ appears 3 times[2]→ appears 2 times
Subarrays of length 2:
[1, 1]→ appears once[1, 2]→ appears once[2, 2]→ appears once[2, 1]→ appears once
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 105
Solutions
Prefix hashes and powers, plus binary search via function. #easy
Language: javascript()DONE
CPU Performance81.21%
x
Memory Performance31.54%
x
/** By Leetcode */
var smallestUniqueSubarray = function (nums) {
const BASE = 911382323;
const n = nums.length;
const hash = new Uint32Array(n + 1);
const powers = new Uint32Array(n + 1);
powers[0] = 1;
// Compute prefix hashes and powers of BASE
for (let i = 0; i < n; ++i) {
hash[i + 1] = (Math.imul(hash[i], BASE) + nums[i]) >>> 0;
powers[i + 1] = Math.imul(powers[i], BASE) >>> 0;
}
const check = (length) => {
const counts = new Map();
for (let left = 0; left + length <= n; ++left) {
const right = left + length;
const key =
(hash[right] - Math.imul(hash[left], powers[length])) >>> 0;
counts.set(key, (counts.get(key) ?? 0) + 1);
}
for (const times of counts.values()) {
if (times === 1) {
return true;
}
}
return false;
};
let lo = 1,
hi = n;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (check(mid)) {
hi = mid;
} else {
lo = mid + 1;
}
}
return lo;
};