Smallest Unique Subarray — Algorithm Visualization & Coding Challenge

Choose Your Learning Path

How would you like to learn today?
Visualize algorithms in real time, explore them step by step, or challenge yourself with a test.Choose a path to focus—or scroll down to preview all options.

🧠 Active Learning

Visualize the algorithm step-by-step with interactive animations in real time.

📖 Passive Learning

Read the full explanation, examples, and starter code at your own pace.

🎮 Challenge Mode

Drag and arrange the algorithm steps in the correct execution order.

Use Cases

🎥 Create YouTube tutorials and structured courses with step-by-step visual explanations

🧠 Practice coding problems on canvas using built-in tools like stacks, queues, pointers, and graphs

✍️ Design algorithms in any programming language, pseudocode, or even your mother tongue

📊 Track your logic and progress directly on your dashboard

● JUMP INTO VISUALIZATION
Watch algorithms run step by step.

Follow every state change, comparison, and transformation as the execution unfolds in real time.

Understanding Smallest Unique Subarray
Detailed explanation and reference materials
PROBLEM OVERVIEW

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 repeatUnderstanding 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:

LengthNumber of windowsHow often each window appearsUnique window?
18[1] ×6, [2] ×2No
27[1,1] ×3, [1,2] ×2, [2,1] ×2No
36[1,1,2] ×2, [1,2,1] ×2, [2,1,1] ×2No
45[1,1,2,1] ×2, [1,2,1,1] ×2, [2,1,1,2] ×1Yes

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

InputOutputWhy
[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]2length 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 between 1 and n.
  • 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 tooKey observation: if a unique window of length L exists, one of length L+1 exists too

If some subarray of length L is unique, then some subarray of length L+1 is also unique (as long as L < 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 start j, dropping the last element from both copies would show the original length-L window at j too. 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 arrayKey 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:

StartWindowContains [2,1,1,2]?Appears
0[1,1,2,1,1]No (indices 0 to 4)2 times
1[1,2,1,1,2]Yes1 time, unique
2[2,1,1,2,1]Yes1 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.

  1. Search range: lo = 1, hi = n.
  2. Pick mid = (lo + hi) / 2.
  3. Run hasUnique(mid), which asks whether some window of length mid appears exactly once.
  4. If YES, the answer is mid or smaller, so hi = mid. If no, the answer is bigger, so lo = mid + 1.
  5. 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

  1. Give every window of length L a number (its hash), so equal windows get equal numbers.
  2. Count each number in a HashMap.
  3. Return true if 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 i with length L: h[i+L] - h[i] * p[L]
  • Everything is taken modulo a prime, and the subtraction is fixed with ((x % M) + M) % M so 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 2Binary search dry run: Round 1 and Round 2

Round 1: lo = 1, hi = 8, mid = floor((1 + 8) / 2) = 4. Windows of length 4:

StartWindowAppears
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:

StartWindowAppears
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 finishBinary search dry run: Round 3 and finish

Round 3: lo = 3, hi = 4, mid = floor((3 + 4) / 2) = 3. Windows of length 3:

StartWindowAppears
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

RoundlohimidUnique window exists?Update
1184Yeshi = 4
2142Nolo = 3
3343Nolo = 4
Finish44answer = 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:

LengthHow often each window appearsUnique window?
1[7] ×4, [8] ×3No
2[7,8] ×3, [8,7] ×3No
3[7,8,7] ×3, [8,7,8] ×2No
4[7,8,7,8] ×2, [8,7,8,7] ×2No
5[7,8,7,8,7] ×2, [8,7,8,7,8] ×1Yes
6[7,8,7,8,7,8] ×1, [8,7,8,7,8,7] ×1Yes
7the whole array ×1Yes

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:

RoundlohimidWindows at midUnique exists?Update
1174[7,8,7,8] ×2, [8,7,8,7] ×2Nolo = 5
2576[7,8,7,8,7,8] ×1, [8,7,8,7,8,7] ×1Yeshi = 6
3565[7,8,7,8,7] ×2, [8,7,8,7,8] ×1Yeshi = 5
Finish55answer = 5

What this second example teaches

  • In the first example the search moved both ways, with hi shrinking first and then lo growing. Here lo jumps up first and then hi comes 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

Java
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

CostWhy
TimeO(n log n)about log n binary search rounds, and each hasUnique pass is O(n)
SpaceO(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 because lo == 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 + M before the final % M gives negative hashes and wrong counts.
  • Overflow: keep the hash arrays as long. Multiplying two values below about 10^9 fits in a long but not in an int.
  • Setting hi = n - 1: this is wrong. Length n can be the answer, so hi must start at n.
  • 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.

Instruction-by-Instruction Breakdown

Understand how to organize your main function, helper functions, and other statements when creating an algorithm visualization in DrawToCode.

Main Function

  1. INPUT : nums = { 1, 1, 2, 1, 1, 2, 1, 1}→Input Sentence
  2. OUTPUT : 4→Output Sentence
  3. public static void main(String[] args) {→Simple Statement
  4. int[][] inputs = { {1, 1, 2, 1, 1, 2, 1, 1}, {7, 8, 7, 8, 7, 8, 7}, {3, 3, 3}, {2, 1, 2, 3, 3}, {1, 1, 2, 2, 1},{9}, {5, 5, 5, 5, 5} };→Variable Value Assigned
  5. int[] expected = {4, 5, 3, 1, 2, 1, 5};→Variable Value Assigned
  6. for (int t = 0; t < inputs.length; t++) {→For loop
  7. int result = smallestUniqueSubarray(inputs[t]);→Other Function Call
  8. String status = (result == expected[t]) ? "PASS" : "FAIL";→Variable Value Assigned
  9. System.out.println("nums = " + Arrays.toString(inputs[t]) + " -> " + result + " (expected " + expected[t] + ") " + status);→Simple Statement
  10. }//Loop End→Loop End
  11. }//Loop End→Loop End

Static Helper Function

  1. static int smallestUniqueSubarray(int[] nums) {→Simple Statement
  2. n = nums.length;→Variable Value Assigned
  3. long base = 100_003L + new Random().nextInt(1_000_000);→Variable Value Assigned
  4. h1 = new long[n + 1];→Variable Value Assigned
  5. h2 = new long[n + 1];→Variable Value Assigned
  6. p1 = new long[n + 1];→Variable Value Assigned
  7. p2 = new long[n + 1];→Variable Value Assigned
  8. p1[0] = 1;→Variable Value Assigned
  9. p2[0] = 1;→Variable Value Assigned
  10. for (int i = 0; i < n; i++) {→For loop
  11. h1[i + 1] = (h1[i] * base + nums[i]) % M1;→Variable Value Assigned
  12. h2[i + 1] = (h2[i] * base + nums[i]) % M2;→Variable Value Assigned
  13. p1[i + 1] = (p1[i] * base) % M1;→Variable Value Assigned
  14. p2[i + 1] = (p2[i] * base) % M2;→Variable Value Assigned
  15. }//Loop End→Loop End
  16. int lo = 1, hi = n;→Variable Value Assigned
  17. while (lo < hi) {→While loop
  18. int mid = (lo + hi) / 2;→Variable Value Assigned
  19. boolean check = hasUnique(mid);→Other Function Call
  20. if (check) {→If Statement
  21. hi = mid;→Variable Value Assigned
  22. }//If End→If End
  23. else {→Else Statement
  24. lo = mid + 1;→Variable Value Assigned
  25. }//Else End→Else End
  26. }//Else End→Else End
  27. return lo;→Return Statement
  28. }//If End→If End

Static Utility Functions, Classes and Global Variables

  1. static boolean hasUnique(int L) {→Simple Statement
  2. Map<Long, Integer> count = new HashMap<>();→Variable Value Assigned
  3. for (int i = 0; i + L <= n; i++) {→For loop
  4. long a = ((h1[i + L] - h1[i] * p1[L]) % M1 + M1) % M1;→Variable Value Assigned
  5. long b = ((h2[i + L] - h2[i] * p2[L]) % M2 + M2) % M2;→Variable Value Assigned
  6. long key = a * M2 + b;→Variable Value Assigned
  7. count.merge(key, 1, Integer::sum);→Variable Value Assigned
  8. }//Loop End→Loop End
  9. for (int c : count.values()) {→For loop
  10. if (c == 1) {→If Statement
  11. return true;→Return Statement
  12. }//If End→If End
  13. }//If End→If End
  14. return false;→Return Statement
  15. }//Loop End→Loop End
  16. static final long M1 = 1_000_000_007L;→Variable Value Assigned
  17. static final long M2 = 998_244_353L;→Variable Value Assigned
  18. static long[] h1, h2, p1, p2;→Simple Statement
  19. static int n;→Simple Statement
Written by Saurabh Patil • B.Tech CSE • Software Developer

Categories
arrays
Binary Search
Hashing
leetcode-problem-of-the-day
java
Reference Link
https://leetcode.com/problems/smallest-unique-subarray/description/
Starter Code
Test, modify, or copy the starter code. Click "Visualize" to import into the canvas.
Understood Algorithm, Test Me now 🎮

Scroll down to play

▼
🧠 Logic Puzzle
Think & Arrange, Don't Just Copy-Paste

Drag and arrange the algorithm steps in the correct execution order instead of spending time typing code letter by letter.

Arrange the Algorithm Correctly 🧩

The algorithm is divided into three logical parts. Carefully rearrange each section in the correct order to form a complete and valid solution.

Don't Know Provided Algorithm ?  

OR

Green text means the instruction is placed in the correct position.

Red text means the instruction is in the wrong position.

Block Colors

Instructions with the same background color indicate particular blocks start and end.

A tick mark means the instruction is correct and locked.

🔒 Locked steps cannot be moved. Only unlocked steps are draggable.

🔊 Enable sound for swap feedback and completion effects.

DrawToCode — Visualize, Practice & Master Algorithms

Learn data structures and algorithms through interactive visualizations. Practice coding problems, track your progress, and understand concepts deeply.

Visualization Board | Problems | About | Contact  | Terms of Service  | Privacy Policy  | 
EmailLinkedInTwitterInstagramGitHub
© 2026 DrawToCode. All rights reserved.