[LeetCode] Smallest Unique Subarray

3934. Smallest Unique Subarray

You are given an integer array nums.

Find the minimumlength 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

vector<int> SA(vector<int>& s) {
int n = s.size(), t = 1;
vector<int> sa(n), tg(n + 1), g(n + 1);
for(int i = 0; i < n; i++) sa[i] = i, g[i] = s[i];
while(t <= n) {
g[n] = -1;
auto cmp = [&](int x, int y) {
if(g[x] == g[y]) return g[x + t] < g[y + t];
return g[x] < g[y];
};

sort(begin(sa), end(sa), cmp);

tg[sa[0]] = 0;
for(int i = 1; i < n; i++) tg[sa[i]] = tg[sa[i-1]] + cmp(sa[i-1], sa[i]);

swap(g,tg);
t <<= 1;
}
return sa;
}

vector<int> LCP(vector<int>& sa, vector<int>& s) {
int n = s.size(), len = 0;
vector<int> rsa(n), lcp(n);
for(int i = 0; i < n; i++) rsa[sa[i]] = i;
for(int i = 0; i < n; i++) {
int k = rsa[i];
if(k) {
int j = sa[k-1];
while(i + len < n and j + len < n and s[i + len] == s[j + len]) ++len;
lcp[k] = len;
if(len) --len;
}
}
vector<int> res(n);
for(int i = 0; i < n; i++) res[i] = lcp[sa[i]];
return lcp;
}

class Solution {
public:
int smallestUniqueSubarray(vector<int>& nums) {
if(nums.size() == 1) return 1;
auto sa = SA(nums);
auto lcp = LCP(sa,nums);
int res = INT_MAX, n = nums.size();
for(int i = 0; i < n; i++) {
if(i == n - 1 or lcp[i+1] <= lcp[i]) {
res = min(res, lcp[i] + 1);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/smallest-unique-subarray/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.