Given a string, find the smallest window length with all distinct characters of the given string. For eg. str = “aabcbcdbca”, then the result would be 4 as of the smallest window will be “dbca” .**Examples:**

Input:aabcbcdbcaOutput:dbcaExplanation:Possible substrings= {aabcbcd, abcbcd, bcdbca, dbca....} Of the set of possible substrings 'dbca' is the shortest substring having all the distinct characters of given string.Input:aaabOutput:abExplanation:Possible substrings={aaab, aab, ab} Of the set of possible substrings 'ab' is the shortest substring having all the distinct characters of given string.

**Solution:** Above problem states that we have to find the smallest window that contains all the distinct characters of the given string even if the smallest string contains repeating elements.

For example, in “aabcbcdb”, the smallest string that contains all the characters is “abcbcd”.** Method 1:** This is the Brute Force method of solving the problem using HashMap.

**Approach :**For solving the problem we first have to find out all the distinct characters present in the string. This can be done using a**HashMap**. The next thing is to generate all the possible substrings. This follows by checking whether a substring generated has all the required characters(stored in the hash_map) or not. If yes, then compare its length with the minimum substring length which follows the above constraints, found till now.*HashMap**:*HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs. To access a value one must know its key. HashMap is known as HashMap because it uses a technique called Hashing. Hashing is a technique of converting a large String to small String that represents the same String. A shorter value helps in indexing and faster searches. HashSet also uses HashMap internally. It internally uses a link list to store key-value pairs already explained in HashSet in detail and further articles.

**Algorithm :**- Store all distinct characters of the given string in a hash_map.
- Take a variable count and initialize it with value 0.
- Generate the substrings using two pointers.
**Now check whether generated substring is valid or not-:**- As soon we find that the character of the substring generated has not been encountered before, increment count by
**1**. - We can use a visited array of
**max_chars**size to find whether the current character has been encountered before or not. - If count is equal to equal to size of hash_map the substring generated is valid
- If it is a valid substring, compare it with the minimum length substring already generated.

- As soon we find that the character of the substring generated has not been encountered before, increment count by

**Pseudo Code:**

maphash_map; for ( i=0 to str.length()) hash_map[str[i]]++;//finding all distinct charaters of string minimum_size=INT_MAX Distinct_chars=hash_map.size() for(i=0 to str.length()) count=0; sub_str=""; visited[256]={0}; for(j=i to n) sub_str+=str[j] if(visited[str[j]]==0) count++ visited[str[j]]=1; if(count==Distinct_chars) end loop if(sub_str.length()<minimum_size&& count==Distinct_chars) ans=sub_str; return ans

**Implementation:**

## CPP

`// C++ program to find the smallest` `// window containing all characters` `// of a pattern.` `#include <bits/stdc++.h>` `using` `namespace` `std;` `const` `int` `MAX_CHARS = 256;` `// Function to find smallest window containing` `// all distinct characters` `string findSubString(string str)` `{` ` ` `int` `n = str.length();` ` ` `// Count all distinct characters.` ` ` `int` `dist_count = 0;` ` ` `unordered_map<` `int` `, ` `int` `> hash_map;` ` ` `for` `(` `int` `i = 0; i < n; i++) {` ` ` `hash_map[str[i]]++;` ` ` `}` ` ` `dist_count = hash_map.size();` ` ` `int` `size = INT_MAX;` ` ` `string res;` ` ` `// Now follow the algorithm discussed in below` ` ` `for` `(` `int` `i = 0; i < n; i++) {` ` ` `int` `count = 0;` ` ` `int` `visited[256] = { 0 };` ` ` `string sub_str = ` `""` `;` ` ` `for` `(` `int` `j = i; j < n; j++) {` ` ` `if` `(visited[str[j]] == 0) {` ` ` `count++;` ` ` `visited[str[j]] = 1;` ` ` `}` ` ` `sub_str += str[j];` ` ` `if` `(count == dist_count)` ` ` `break` `;` ` ` `}` ` ` `if` `(sub_str.length() < size && count == dist_count)` ` ` `{` ` ` `res = sub_str;` ` ` `size=res.length();` ` ` `}` ` ` `}` ` ` `return` `res;` `}` `// Driver Code` `int` `main()` `{` ` ` `string str = ` `"aabcbcdbca"` `;` ` ` `cout << ` `"Smallest window containing all distinct"` ` ` `" characters is: "` ` ` `<< findSubString(str);` ` ` `return` `0;` `}` |

## Java

`import` `java.io.*;` `import` `java.util.*;` `// Java program to find the smallest` `// window containing all characters` `// of a pattern.` `class` `GFG` `{` ` ` ` ` `// Function to find smallest window containing` ` ` `// all distinct characters` ` ` `public` `static` `String findSubString(String str)` ` ` `{` ` ` `int` `n = str.length();` ` ` ` ` `// Count all distinct characters.` ` ` `int` `dist_count = ` `0` `;` ` ` `HashMap<Character, Integer> mp = ` `new` `HashMap<>();` ` ` `for` `(` `int` `i = ` `0` `; i < n; i++)` ` ` `{` ` ` `if` `(mp.containsKey(str.charAt(i)))` ` ` `{` ` ` `Integer a = mp.get(str.charAt(i));` ` ` `mp.put(str.charAt(i),a+` `1` `); ` ` ` `}` ` ` `else` ` ` `{` ` ` `mp.put(str.charAt(i), ` `1` `);` ` ` `}` ` ` `}` ` ` `dist_count = mp.size();` ` ` `int` `size = Integer.MAX_VALUE;` ` ` `String res = ` `""` `;` ` ` ` ` `// Now follow the algorithm discussed in below` ` ` `for` `(` `int` `i = ` `0` `; i < n; i++)` ` ` `{` ` ` `int` `count = ` `0` `;` ` ` `int` `visited[] = ` `new` `int` `[` `256` `];` ` ` `for` `(` `int` `j = ` `0` `; j < ` `256` `; j++)` ` ` `visited[j] = ` `0` `;` ` ` `String sub_str = ` `""` `;` ` ` `for` `(` `int` `j = i; j < n; j++)` ` ` `{` ` ` `if` `(visited[str.charAt(j)] == ` `0` `)` ` ` `{` ` ` `count++;` ` ` `visited[str.charAt(j)] = ` `1` `;` ` ` `}` ` ` `sub_str += str.charAt(j);` ` ` `if` `(count == dist_count)` ` ` `break` `;` ` ` `}` ` ` `if` `(sub_str.length() < size && count == dist_count)` ` ` `{` ` ` `res = sub_str;` ` ` `size=res.length();` ` ` `}` ` ` `}` ` ` `return` `res;` ` ` `}` ` ` ` ` `// Driver code` ` ` `public` `static` `void` `main (String[] args)` ` ` `{` ` ` `String str = ` `"aabcbcdbca"` `;` ` ` `System.out.println(` `"Smallest window containing all distinct"` `+` ` ` `" characters is: "` `+ findSubString(str)) ;` ` ` `}` `}` `// This code is contributed by Manu Pathria` |

**Output**

Smallest window containing all distinct characters is: dbca

**Complexity Analysis:****Time Complexity:**O(N^2).

This time is required to generate all possible sub-strings of a string of length “N”.**Space Complexity:**O(N).

As a**hash_map**has been used of size N.

** Method 2:** Here we have used Sliding Window technique to arrive at the solution. This technique shows how a nested for loop in few problems can be converted to single for loop and hence reducing the time complexity.

**Approach:**Basically a window of characters is maintained by using two pointers namely**start**and**end**. These**start**and**end**pointers can be used to shrink and increase the size of window respectively. Whenever the window contains all characters of given string, the window is shrinked from left side to remove extra characters and then its length is compared with the smallest window found so far.

If in the present window, no more characters can be deleted then we start increasing the size of the window using the**end**until all the distinct characters present in the string are also there in the window. Finally, find the minimum size of each window.

**Algorithm :**- Maintain an array
**(visited)**of maximum possible characters (256 characters) and as soon as we find any in the string, mark that index in the array**(this is to count all distinct characters in the string).** - Take two pointers
**start**and**end**which will mark the start and end of window. - Take a
**counter=0**which will be used to count distinct characters in the window. - Now start reading the characters of the given string and if we come across a character which has not been visited yet increment the counter by
**1**. - If the
**counter**is equal to total number of distinct characters, Try to shrink the window. **For shrinking the window -:**- If the
**frequency**of character at start pointer is**greater than 1**increment the pointer as it is redundant. - Now compare the length of present window with the minimum window length.

- If the

- Maintain an array
**Implementation:**

## C++

`// C++ program to find the smallest` `// window containing all characters` `// of a pattern.` `#include <bits/stdc++.h>` `using` `namespace` `std;` `const` `int` `MAX_CHARS = 256;` `// Function to find smallest window containing` `// all distinct characters` `string findSubString(string str)` `{` ` ` `int` `n = str.length();` ` ` `// Count all distinct characters.` ` ` `int` `dist_count = 0;` ` ` `bool` `visited[MAX_CHARS] = { ` `false` `};` ` ` `for` `(` `int` `i = 0; i < n; i++) {` ` ` `if` `(visited[str[i]] == ` `false` `) {` ` ` `visited[str[i]] = ` `true` `;` ` ` `dist_count++;` ` ` `}` ` ` `}` ` ` `// Now follow the algorithm discussed in below` ` ` `// post. We basically maintain a window of characters` ` ` `// that contains all characters of given string.` ` ` `int` `start = 0, start_index = -1, min_len = INT_MAX;` ` ` `int` `count = 0;` ` ` `int` `curr_count[MAX_CHARS] = { 0 };` ` ` `for` `(` `int` `j = 0; j < n; j++) {` ` ` `// Count occurrence of characters of string` ` ` `curr_count[str[j]]++;` ` ` `// If any distinct character matched,` ` ` `// then increment count` ` ` `if` `(curr_count[str[j]] == 1)` ` ` `count++;` ` ` `// if all the characters are matched` ` ` `if` `(count == dist_count) {` ` ` `// Try to minimize the window i.e., check if` ` ` `// any character is occurring more no. of times` ` ` `// than its occurrence in pattern, if yes` ` ` `// then remove it from starting and also remove` ` ` `// the useless characters.` ` ` `while` `(curr_count[str[start]] > 1) {` ` ` `if` `(curr_count[str[start]] > 1)` ` ` `curr_count[str[start]]--;` ` ` `start++;` ` ` `}` ` ` `// Update window size` ` ` `int` `len_window = j - start + 1;` ` ` `if` `(min_len > len_window) {` ` ` `min_len = len_window;` ` ` `start_index = start;` ` ` `}` ` ` `}` ` ` `}` ` ` `// Return substring starting from start_index` ` ` `// and length min_len` ` ` `return` `str.substr(start_index, min_len);` `}` `// Driver code` `int` `main()` `{` ` ` `string str = ` `"aabcbcdbca"` `;` ` ` `cout << ` `"Smallest window containing all distinct"` ` ` `" characters is: "` ` ` `<< findSubString(str);` ` ` `return` `0;` `}` |

## Java

`// Java program to find the smallest window containing` `// all characters of a pattern.` `import` `java.util.Arrays;` `public` `class` `GFG {` ` ` `static` `final` `int` `MAX_CHARS = ` `256` `;` ` ` `// Function to find smallest window containing` ` ` `// all distinct characters` ` ` `static` `String findSubString(String str)` ` ` `{` ` ` `int` `n = str.length();` ` ` `// Count all distinct characters.` ` ` `int` `dist_count = ` `0` `;` ` ` `boolean` `[] visited = ` `new` `boolean` `[MAX_CHARS];` ` ` `Arrays.fill(visited, ` `false` `);` ` ` `for` `(` `int` `i = ` `0` `; i < n; i++) {` ` ` `if` `(visited[str.charAt(i)] == ` `false` `) {` ` ` `visited[str.charAt(i)] = ` `true` `;` ` ` `dist_count++;` ` ` `}` ` ` `}` ` ` `// Now follow the algorithm discussed in below` ` ` `// post. We basically maintain a window of characters` ` ` `// that contains all characters of given string.` ` ` `int` `start = ` `0` `, start_index = -` `1` `;` ` ` `int` `min_len = Integer.MAX_VALUE;` ` ` `int` `count = ` `0` `;` ` ` `int` `[] curr_count = ` `new` `int` `[MAX_CHARS];` ` ` `for` `(` `int` `j = ` `0` `; j < n; j++) {` ` ` `// Count occurrence of characters of string` ` ` `curr_count[str.charAt(j)]++;` ` ` `// If any distinct character matched,` ` ` `// then increment count` ` ` `if` `(curr_count[str.charAt(j)] == ` `1` `)` ` ` `count++;` ` ` `// if all the characters are matched` ` ` `if` `(count == dist_count) {` ` ` `// Try to minimize the window i.e., check if` ` ` `// any character is occurring more no. of times` ` ` `// than its occurrence in pattern, if yes` ` ` `// then remove it from starting and also remove` ` ` `// the useless characters.` ` ` `while` `(curr_count[str.charAt(start)] > ` `1` `) {` ` ` `if` `(curr_count[str.charAt(start)] > ` `1` `)` ` ` `curr_count[str.charAt(start)]--;` ` ` `start++;` ` ` `}` ` ` `// Update window size` ` ` `int` `len_window = j - start + ` `1` `;` ` ` `if` `(min_len > len_window) {` ` ` `min_len = len_window;` ` ` `start_index = start;` ` ` `}` ` ` `}` ` ` `}` ` ` `// Return substring starting from start_index` ` ` `// and length min_len` ` ` `return` `str.substring(start_index, start_index + min_len);` ` ` `}` ` ` `// Driver code` ` ` `public` `static` `void` `main(String args[])` ` ` `{` ` ` `String str = ` `"aabcbcdbca"` `;` ` ` `System.out.println(` `"Smallest window containing all distinct"` ` ` `+ ` `" characters is: "` `+ findSubString(str));` ` ` `}` `}` `// This code is contributed by Sumit Ghosh` |

## Python

`# Python program to find the smallest` `# window containing` `# all characters of a pattern` `from` `collections ` `import` `defaultdict` `MAX_CHARS ` `=` `256` `# Function to find smallest window` `# containing all distinct characters` `def` `findSubString(strr):` ` ` ` ` `n ` `=` `len` `(strr)` ` ` ` ` `# Count all distinct characters.` ` ` `dist_count ` `=` `len` `(` `set` `([x ` `for` `x ` `in` `strr]))` ` ` ` ` `curr_count ` `=` `defaultdict(` `lambda` `: ` `0` `)` ` ` `count ` `=` `0` ` ` `start ` `=` `0` ` ` `min_len ` `=` `n` ` ` ` ` `# Now follow the algorithm discussed in below` ` ` `# post. We basically maintain a window of characters` ` ` `# that contains all characters of given string.` ` ` `for` `j ` `in` `range` `(n):` ` ` `curr_count[strr[j]] ` `+` `=` `1` ` ` ` ` `# If any distinct character matched,` ` ` `# then increment count` ` ` `if` `curr_count[strr[j]] ` `=` `=` `1` `:` ` ` `count ` `+` `=` `1` ` ` ` ` `# Try to minimize the window i.e., check if` ` ` `# any character is occurring more no. of times` ` ` `# than its occurrence in pattern, if yes` ` ` `# then remove it from starting and also remove` ` ` `# the useless characters.` ` ` `if` `count ` `=` `=` `dist_count:` ` ` `while` `curr_count[strr[start]] > ` `1` `:` ` ` `if` `curr_count[strr[start]] > ` `1` `:` ` ` `curr_count[strr[start]] ` `-` `=` `1` ` ` ` ` `start ` `+` `=` `1` ` ` ` ` `# Update window size` ` ` `len_window ` `=` `j ` `-` `start ` `+` `1` ` ` ` ` `if` `min_len > len_window:` ` ` `min_len ` `=` `len_window` ` ` `start_index ` `=` `start` ` ` `# Return substring starting from start_index` ` ` `# and length min_len """` ` ` `return` `str` `(strr[start_index: start_index ` `+` ` ` `min_len])` ` ` `# Driver code` `if` `__name__` `=` `=` `'__main__'` `:` ` ` ` ` `print` `(` `"Smallest window containing "` ` ` `"all distinct characters is: {}"` `.` `format` `(` ` ` `findSubString(` `"aabcbcdbca"` `)))` `# This code is contributed by ` `# Subhrajit` |

## C#

`// C# program to find the smallest window containing` `// all characters of a pattern.` `using` `System;` `class` `GFG {` ` ` `static` `int` `MAX_CHARS = 256;` ` ` `// Function to find smallest window containing` ` ` `// all distinct characters` ` ` `static` `string` `findSubString(` `string` `str)` ` ` `{` ` ` `int` `n = str.Length;` ` ` `// Count all distinct characters.` ` ` `int` `dist_count = 0;` ` ` `bool` `[] visited = ` `new` `bool` `[MAX_CHARS];` ` ` `for` `(` `int` `i = 0; i < n; i++) {` ` ` `if` `(visited[str[i]] == ` `false` `) {` ` ` `visited[str[i]] = ` `true` `;` ` ` `dist_count++;` ` ` `}` ` ` `}` ` ` `// Now follow the algorithm discussed in below` ` ` `// post. We basically maintain a window of characters` ` ` `// that contains all characters of given string.` ` ` `int` `start = 0, start_index = -1, min_len = ` `int` `.MaxValue;` ` ` `int` `count = 0;` ` ` `int` `[] curr_count = ` `new` `int` `[MAX_CHARS];` ` ` `for` `(` `int` `j = 0; j < n; j++) {` ` ` `// Count occurrence of characters of string` ` ` `curr_count[str[j]]++;` ` ` `// If any distinct character matched,` ` ` `// then increment count` ` ` `if` `(curr_count[str[j]] == 1)` ` ` `count++;` ` ` `// if all the characters are matched` ` ` `if` `(count == dist_count) {` ` ` `// Try to minimize the window i.e., check if` ` ` `// any character is occurring more no. of times` ` ` `// than its occurrence in pattern, if yes` ` ` `// then remove it from starting and also remove` ` ` `// the useless characters.` ` ` `while` `(curr_count[str[start]] > 1) {` ` ` `if` `(curr_count[str[start]] > 1)` ` ` `curr_count[str[start]]--;` ` ` `start++;` ` ` `}` ` ` `// Update window size` ` ` `int` `len_window = j - start + 1;` ` ` `if` `(min_len > len_window) {` ` ` `min_len = len_window;` ` ` `start_index = start;` ` ` `}` ` ` `}` ` ` `}` ` ` `// Return substring starting from start_index` ` ` `// and length min_len` ` ` `return` `str.Substring(start_index, min_len);` ` ` `}` ` ` `// Driver code` ` ` `public` `static` `void` `Main(String[] args)` ` ` `{` ` ` `string` `str = ` `"aabcbcdbca"` `;` ` ` `Console.WriteLine(` `"Smallest window containing all distinct"` ` ` `+ ` `" characters is: "` `+ findSubString(str));` ` ` `}` `}` `// This code contributed by Rajput-Ji` |

**Output:**

Smallest window containing all distinct characters is dbca

**Complexity Analysis:****Time Complexity:**O(N).

As the string is traversed using two pointers only once.**Space Complexity:**O(N).

As a**hash_map**is used of size N

**Related Article:**

- Length of the smallest sub-string consisting of maximum distinct characters
- https://www.geeksforgeeks.org/find-the-smallest-window-in-a-string-containing-all-characters-of-another-string/

This article is contributed by **Sahil Chhabra**. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the **DSA Self Paced Course** at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer **Complete Interview Preparation Course****.**

In case you wish to attend live classes with industry experts, please refer **Geeks Classes Live**