Smallest Unique Subarray
LeetCode 3934
· Hard · Array · Hash Table · Binary Search · Rolling Hash · Suffix Array
1. Understand the problem
Understanding the problem: windows of every length and which ones repeat
You are given an integer array nums. A subarray is a contiguous slice of the array. Two subarrays are identical when they have the same length and the same elements in the same positions.
A subarray is unique when no other subarray of nums is identical to it. In other words, it appears exactly once.
Task: return the smallest length L for which at least one unique subarray of length L exists.
Constraints: 1 <= nums.length <= 10^5 and 1 <= nums[i] <= 10^5.
The example we will use throughout
Input: nums = [1,1,2,1,1,2,1,1]
Output: 4
Look at every length, from shortest to longest, and count how often each window appears:
| Length | Number of windows | How often each window appears | Unique window? |
|---|---|---|---|
| 1 | 8 | [1] ×6, [2] ×2 | No |
| 2 | 7 | [1,1] ×3, [1,2] ×2, [2,1] ×2 | No |
| 3 | 6 | [1,1,2] ×2, [1,2,1] ×2, [2,1,1] ×2 | No |
| 4 | 5 | [1,1,2,1] ×2, [1,2,1,1] ×2, [2,1,1,2] ×1 | Yes |
The window [2,1,1,2] (indices 2 to 5) appears only once, and no shorter length has a unique window, so the answer is 4.
Quick sanity checks from the problem statement
| Input | Output | Why |
|---|---|---|
[3,3,3] | 3 | [3] ×3 and [3,3] ×2 both repeat, so only the whole array is unique |
[2,1,2,3,3] | 1 | [1] appears once |
[1,1,2,2,1] | 2 | length 1 repeats, but [1,1], [1,2], [2,2], [2,1] each appear once |
Two facts worth noting
- The whole array is the only window of length
n, so it is always unique. The answer is always between1andn. - A brute force approach tries every length and compares every window. There are about n²/2 subarrays and comparing them costs even more, which is far too slow for n = 100,000.
2. Key observation: uniqueness never disappears as L grows
Key observation: if a unique window of length L exists, one of length L+1 exists too
If some subarray of length
Lis unique, then some subarray of lengthL+1is also unique (as long asL < n).
Why it is true
Suppose the window at start i with length L is unique.
- Extend to the right to get
nums[i..i+L]. If this longer window appeared at another startj, dropping the last element from both copies would show the original length-Lwindow atjtoo. That contradicts uniqueness. - Extend to the left to get
nums[i-1..i+L-1]. If it appeared at another start, dropping the first element from both copies would again show a second copy of the original window. - Since
L < n, at least one of the two extensions always exists.
So a unique window can only become more specific when it grows. It can never start repeating.
Why the claim says "some" and not "all"
The guarantee only covers longer windows that contain the unique one. Other longer windows can still repeat.
Key observation with the example
Key observation applied to the example array
At L = 4 the only unique window is [2,1,1,2], at start 2 (indices 2 to 5). Now look at L = 5:
| Start | Window | Contains [2,1,1,2]? | Appears |
|---|---|---|---|
| 0 | [1,1,2,1,1] | No (indices 0 to 4) | 2 times |
| 1 | [1,2,1,1,2] | Yes | 1 time, unique |
| 2 | [2,1,1,2,1] | Yes | 1 time, unique |
| 3 | [1,1,2,1,1] | No (indices 3 to 7) | 2 times |
The two windows that contain [2,1,1,2] stay unique. The two that do not contain it still repeat. This is exactly why the claim says "some".
The pattern this creates
For any array, asking "does a unique window of length L exist?" gives answers in this shape:
L: 1 2 3 4 5 6 7 8
exists? no no no YES YES YES YES YES
It always runs no, no, ..., no, YES, YES, ..., YES, and it always ends in YES at L = n. It never goes YES and then no.
3. The plan: binary search on the length
Because the answers flip from no to YES exactly once, we can binary search on the length L instead of trying every length.
- Search range:
lo = 1,hi = n. - Pick
mid = (lo + hi) / 2. - Run
hasUnique(mid), which asks whether some window of lengthmidappears exactly once. - If YES, the answer is
midor smaller, sohi = mid. If no, the answer is bigger, solo = mid + 1. - Stop when
lo == hi. That value is the answer.
The check only needs "does at least one window have count 1?". It never needs to track which window is unique, because the proof above guarantees that uniqueness at L carries over to L+1.
How hasUnique(L) works
- Give every window of length
La number (its hash), so equal windows get equal numbers. - Count each number in a
HashMap. - Return
trueif any count is exactly 1.
Comparing whole subarrays would be too slow, so each window is turned into a single number with a rolling hash.
The rolling hash in four lines
- Prefix hash:
h[i+1] = h[i] * base + nums[i] - Powers:
p[i] = base^i - Hash of the window starting at
iwith lengthL:h[i+L] - h[i] * p[L] - Everything is taken modulo a prime, and the subtraction is fixed with
((x % M) + M) % Mso it never goes negative.
Tiny base-10 example for [1,1,2,1]: the prefix hashes are [0, 1, 11, 112, 1121]. The window [1,2] at start 1 has hash 112 - 1 * 100 = 12, which is just its digits written together.
Two moduli and a combined key
The Java code computes the hash under two different primes (1_000_000_007 and 998_244_353) with a random base. Two different windows would need to collide under both primes at once to be confused, which is extremely unlikely. The two results are merged into one long key with a * M2 + b, so the HashMap stores one number per window.
4. Dry run on the example
nums = [1,1,2,1,1,2,1,1], so n = 8. We start with lo = 1 and hi = 8.
Round 1 and Round 2
Binary search dry run: Round 1 and Round 2
Round 1: lo = 1, hi = 8, mid = floor((1 + 8) / 2) = 4. Windows of length 4:
| Start | Window | Appears |
|---|---|---|
| 0 | [1,1,2,1] | 2 |
| 1 | [1,2,1,1] | 2 |
| 2 | [2,1,1,2] | 1 |
| 3 | [1,1,2,1] | 2 |
| 4 | [1,2,1,1] | 2 |
One window has count 1, so hasUnique(4) is true. The answer is 4 or smaller, so hi = 4.
Round 2: lo = 1, hi = 4, mid = floor((1 + 4) / 2) = 2. Windows of length 2:
| Start | Window | Appears |
|---|---|---|
| 0 | [1,1] | 3 |
| 1 | [1,2] | 2 |
| 2 | [2,1] | 2 |
| 3 | [1,1] | 3 |
| 4 | [1,2] | 2 |
| 5 | [2,1] | 2 |
| 6 | [1,1] | 3 |
No count equals 1, so hasUnique(2) is false. The answer is bigger than 2, so lo = 3.
Round 3 and finish
Binary search dry run: Round 3 and finish
Round 3: lo = 3, hi = 4, mid = floor((3 + 4) / 2) = 3. Windows of length 3:
| Start | Window | Appears |
|---|---|---|
| 0 | [1,1,2] | 2 |
| 1 | [1,2,1] | 2 |
| 2 | [2,1,1] | 2 |
| 3 | [1,1,2] | 2 |
| 4 | [1,2,1] | 2 |
| 5 | [2,1,1] | 2 |
Every window repeats, so hasUnique(3) is false and lo = 4.
Finish: lo = hi = 4, so the search stops and the answer is 4.
Summary of the rounds
| Round | lo | hi | mid | Unique window exists? | Update |
|---|---|---|---|---|---|
| 1 | 1 | 8 | 4 | Yes | hi = 4 |
| 2 | 1 | 4 | 2 | No | lo = 3 |
| 3 | 3 | 4 | 3 | No | lo = 4 |
| Finish | 4 | 4 | answer = 4 |
Only 3 of the 8 lengths were tested. Lengths 1, 5, 6, 7, and 8 were skipped, because the monotonic pattern already tells us what they would return.
5. A completely different input
Input: nums = [7,8,7,8,7,8,7]
Output: 5
This array alternates, so every short window shows up again two positions later. Here is the full picture for every length, so you can see why the answer is 5:
| Length | How often each window appears | Unique window? |
|---|---|---|
| 1 | [7] ×4, [8] ×3 | No |
| 2 | [7,8] ×3, [8,7] ×3 | No |
| 3 | [7,8,7] ×3, [8,7,8] ×2 | No |
| 4 | [7,8,7,8] ×2, [8,7,8,7] ×2 | No |
| 5 | [7,8,7,8,7] ×2, [8,7,8,7,8] ×1 | Yes |
| 6 | [7,8,7,8,7,8] ×1, [8,7,8,7,8,7] ×1 | Yes |
| 7 | the whole array ×1 | Yes |
The unique window at length 5 is [8,7,8,7,8] (indices 1 to 5). Its copy would have to start at index 3, but that would run past the end of the array, and starting at index -1 is impossible. The other two length-5 windows, at starts 0 and 2, are identical to each other.
The pattern is no, no, no, no, YES, YES, YES, which has the same single flip as before. Now the binary search with n = 7:
| Round | lo | hi | mid | Windows at mid | Unique exists? | Update |
|---|---|---|---|---|---|---|
| 1 | 1 | 7 | 4 | [7,8,7,8] ×2, [8,7,8,7] ×2 | No | lo = 5 |
| 2 | 5 | 7 | 6 | [7,8,7,8,7,8] ×1, [8,7,8,7,8,7] ×1 | Yes | hi = 6 |
| 3 | 5 | 6 | 5 | [7,8,7,8,7] ×2, [8,7,8,7,8] ×1 | Yes | hi = 5 |
| Finish | 5 | 5 | answer = 5 |
What this second example teaches
- In the first example the search moved both ways, with
hishrinking first and thenlogrowing. Herelojumps up first and thenhicomes down, but the rule is the same each time. - Round 3 tested length 5 even though length 6 was already YES. The search needs to confirm that nothing shorter works, and it does that by testing the length just below.
- Highly repetitive arrays push the answer toward
n. In the extreme case,[5,5,5,5,5]has answer 5, since only the whole array is unique.
6. Java solution
import java.util.*;
class Solution {
static final long M1 = 1_000_000_007L;
static final long M2 = 998_244_353L;
long[] h1, h2, p1, p2;
int n;
public int smallestUniqueSubarray(int[] nums) {
n = nums.length;
long base = 100_003L + new Random().nextInt(1_000_000);
h1 = new long[n + 1];
h2 = new long[n + 1];
p1 = new long[n + 1];
p2 = new long[n + 1];
p1[0] = 1;
p2[0] = 1;
// prefix hashes: hash of nums[0..i-1]
for (int i = 0; i < n; i++) {
h1[i + 1] = (h1[i] * base + nums[i]) % M1;
h2[i + 1] = (h2[i] * base + nums[i]) % M2;
p1[i + 1] = (p1[i] * base) % M1;
p2[i + 1] = (p2[i] * base) % M2;
}
// binary search on the length
int lo = 1, hi = n;
while (lo < hi) {
int mid = (lo + hi) / 2;
if (hasUnique(mid)) hi = mid; // works, try shorter
else lo = mid + 1; // fails, need longer
}
return lo;
}
// Is there a window of length L that appears exactly once?
private boolean hasUnique(int L) {
Map<Long, Integer> count = new HashMap<>();
for (int i = 0; i + L <= n; i++) {
long a = ((h1[i + L] - h1[i] * p1[L]) % M1 + M1) % M1;
long b = ((h2[i + L] - h2[i] * p2[L]) % M2 + M2) % M2;
long key = a * M2 + b; // combine both hashes into one key
count.merge(key, 1, Integer::sum);
}
for (int c : count.values()) {
if (c == 1) return true;
}
return false;
}
}
7. Complexity
| Cost | Why | |
|---|---|---|
| Time | O(n log n) | about log n binary search rounds, and each hasUnique pass is O(n) |
| Space | O(n) | four prefix and power arrays plus the HashMap |
For n = 100,000 the search takes at most 17 rounds.
8. Edge cases and common mistakes
- Single element:
[9]returns 1. The loop never runs becauselo == hi == 1. - All elements equal: the answer is
n, because only the whole array appears once. - Some value appears exactly once: the answer is 1.
- Negative remainders: forgetting
+ Mbefore the final% Mgives negative hashes and wrong counts. - Overflow: keep the hash arrays as
long. Multiplying two values below about 10^9 fits in alongbut not in anint. - Setting
hi = n - 1: this is wrong. Lengthncan be the answer, sohimust start atn. - A single fixed modulus and base: collisions become realistic. Use two primes and a random base.
9. Key takeaways
- The pattern is binary search on the answer plus a rolling hash. The same pattern solves Longest Duplicate Substring (LeetCode 1044), Longest Repeating Substring (LeetCode 1062), and Longest Common Subpath (LeetCode 1923).
- Monotonicity is what makes binary search legal here. Always ask whether the yes/no answer flips only once as the value grows.
- "Some" is enough. The check only asks whether at least one window is unique.
- A deterministic alternative uses a suffix array and an LCP array. For each suffix, the shortest unique prefix length is
max(lcp with previous, lcp with next) + 1, counted only if it fits in the suffix. The answer is the minimum over all suffixes. It avoids hash collisions but takes more code.