- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 55 lines of C++ from the credited upstream file smallest-unique-subarray.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 5 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 int smallestUniqueSubarray(vector<int>& nums) {8 static const int64_t MOD = 1e9 + 7;9 static const int64_t B = 29;10 const int n = size(nums);11 const auto& binary_search = [](auto left, auto right, const auto& check) {12 while (left <= right) {13 const auto& mid = left + (right - left) / 2;14 if (check(mid)) {15 right = mid - 1;16 } else {17 left = mid + 1;18 }19 }20 return left;21 };22 23 vector<int64_t> prefix(n + 1);24 for (int i = 0; i + 1 < size(prefix); ++i) {25 prefix[i + 1] = (prefix[i] * B + nums[i]) % MOD;26 }27 vector<int64_t> base(n + 1, 1);28 for (int i = 0; i + 1 < size(base); ++i) {29 base[i + 1] = (base[i] * B) % MOD;30 }31 32 const auto& get_hash = [&](int l, int r) {33 if (l > r) {34 return static_cast<int64_t>(0);35 }36 return (prefix[r + 1] - prefix[l] * base[r - l + 1] % MOD + MOD) % MOD;37 };38 39 const auto& check = [&](int l) {40 unordered_map<int64_t, int> cnt;41 for (int i = 0; i + l - 1 < n; ++i) {42 ++cnt[get_hash(i, i + l - 1)];43 }44 for (const auto& [_, x] : cnt) {45 if (x == 1) {46 return true;47 }48 }49 return false;50 };51 52 return binary_search(1, n - 1, check);53 }54};55