Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find the smallest substring containing all distinct characters

Given a string, find the length of the smallest substring that contains all distinct characters present in the original string.

Python practice15 minStrings – Sliding Window & FrequencyIntermediateLast updated March 25, 2026

Problem statement

You are given a string s. Determine the length of the smallest contiguous substring of s that contains every distinct character that appears anywhere in s. If the input string is empty, return 0. For example, if s = "aabcbcdbca", the distinct characters in s are {a, b, c, d}. The smallest substring that contains all four is "dbca" which has length 4. Your function should return the length of such a substring.

Task

Use the sliding window and frequency counting to find the minimum-length window that contains every unique character from the full string.

Examples

Example 1

Input

aabcbcdbca

Output

4

Distinct characters are {a,b,c,d}. Smallest window that contains them all is "dbca" with length 4.

Input format

A single string s.

Output format

An integer representing the length of the smallest substring containing all distinct characters from s. Return 0 for an empty string.

Constraints

- 0 <= len(s) <= 10^5 - s may contain arbitrary characters (letters, digits, punctuation). Solution should be O(n) time and O(m) space where m is the size of the charset encountered.

Samples

Sample 1

Input

aabcbcdbca

Output

4

Distinct characters are {a,b,c,d}. Smallest window length containing them all is 4.