Problem Summary

You’re given a string s made up of only '0', '1', and '2'.

Your task:
Find the length of the smallest substring that contains all three characters at least once.

If it’s not possible, return -1.

Key Insight

Instead of checking all substrings (which is slow), we use the Sliding Window technique.

Why Sliding Window?

Because:

Concept Explained

Think of a window (substring) defined by two pointers:

[left .... right]

Step 1: Expand Window

Move right forward and include characters.

Step 2: Check Validity

If the window contains:

Then it's valid.

Step 3: Shrink Window

Move left forward to minimize the window while keeping it valid.

Example Walkthrough

Input:

s = "10212"

Step-by-step:

Output:

3

Another Example

Input:

s = "12121"

There is no '0' in the string.

Output:

-1

Algorithm

Expand right:

If all 3 characters are present:

Repeat until end

Code (Java)

class Solution {
    public int smallestSubstring(String s) {
        int n = s.length();
        
        int[] count = new int[3];
        int left = 0, minLen = Integer.MAX_VALUE;
        int unique = 0;

        for (int right = 0; right < n; right++) {
            int idx = s.charAt(right) - '0';

            if (count[idx] == 0) unique++;
            count[idx]++;

            while (unique == 3) {
                minLen = Math.min(minLen, right - left + 1);

                int leftIdx = s.charAt(left) - '0';
                count[leftIdx]--;

                if (count[leftIdx] == 0) unique--;
                left++;
            }
        }

        return minLen == Integer.MAX_VALUE ? -1 : minLen;
    }
}

Complexity

Key Takeaways

Always:

Works for many problems like:

Summary

This article explains how to find the smallest substring containing all characters '0', '1', and '2' using a sliding window approach, where the window dynamically expands and shrinks to maintain validity and achieve optimal performance in linear time with constant space.