Smallest substring occurring only once in a given string

18 Apr, 2022
Given a string S consisting of N lowercase alphabets, the task is to find the length of the smallest substring in S whose occurrence is exactly 1.
Examples:
Input: S = “abaaba”Output: 2Explanation: The smallest substring in the string S, whose occurrence is exactly 1 is “aa” . Length of this substring is 2.Therefore, print 2.
Input: S = “zyzyzyz”Output: 5
Approach: To solve the problem, the idea is to generate all possible substring of the given string S and store the frequency of each substring in a HashMap. Now, traverse the HashMap and print the substring of minimum length whose frequency is 1. 
Below is the implementation of the above approach:
C++
Java
Python3
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the smallest// substring occurring only onceint smallestSubstring(string a){     // Stores all occurrences    vector<string> subStrings;    int n = a.size();    // Generate all the substrings    for (int i = 0; i < n; i++)        for (int len = 1; len <= n - i; len++)            subStrings.push_back(a.substr(i, len));     // Take into account    // all the substrings    map<string,int> subStringsFreq;    for(string i: subStrings) {        subStringsFreq[i]++;    }     // Iterate over all    // unique substrings    int ans = INT_MAX;    for (auto str : subStringsFreq)    {        if (str.second == 1){            //Find minimum length of substring            int str_len = str.first.size();            ans = min(ans, str_len);        }    }       // return 0 if no such substring exists    return ans == INT_MAX ? 0 : ans;} // Driver Codeint main(){  string S = "ababaabba";  cout<<smallestSubstring(S);  return 0;} // This code is contributed by mohit kumar 29.
// Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG{ // Function to find the smallest// substring occurring only oncestatic int smallestSubstring(String a){         // Stores all occurrences    ArrayList<String> a1 = new ArrayList<>();     // Generate all the substrings    for(int i = 0; i < a.length(); i++)    {        for(int j = i + 1; j <= a.length(); j++)        {                         // Avoid multiple occurences            if (i != j)                             // Append all substrings                a1.add(a.substring(i, j));        }    }     // Take into account    // all the substrings    TreeMap<String, Integer> a2 = new TreeMap<>();    for(String s : a1)        a2.put(s, a2.getOrDefault(s, 0) + 1);     ArrayList<String> freshlist = new ArrayList<>();     // Iterate over all    // unique substrings    for(String s : a2.keySet())    {                 // If frequency is 1        if (a2.get(s) == 1)             // Append into fresh list            freshlist.add(s);    }     // Initialize a dictionary    TreeMap<String, Integer> dictionary = new TreeMap<>();     for(String s : freshlist)    {                 // Append the keys        dictionary.put(s, s.length());    }     ArrayList<Integer> newlist = new ArrayList<>();     // Traverse the dictionary    for(String s : dictionary.keySet())        newlist.add(dictionary.get(s));     int ans = Integer.MAX_VALUE;     for(int i : newlist)        ans = Math.min(ans, i);     // Return the minimum of dictionary    return ans == Integer.MAX_VALUE ? 0 : ans;} // Driver Codepublic static void main(String[] args){    String S = "ababaabba";         System.out.println(smallestSubstring(S));}} // This code is contributed by Kingash
# Python3 program of the above approachfrom collections import Counter # Function to find the smallest# substring occurring only oncedef smallestSubstring(a):       # Stores all occurrences    a1 = []          # Generate all the substrings    for i in range(len(a)):        for j in range(i+1, len(a)):                       # Avoid multiple occurrences            if i != j:                                   # Append all substrings                a1.append(a[i:j+1])                      # Take into account    # all the substrings    a2 = Counter(a1)     freshlist = []         # Iterate over all    # unique substrings    for i in a2:                  # If frequency is 1        if a2[i] == 1:                       # Append into fresh list            freshlist.append(i)                 # Initialize a dictionary    dictionary = dict()          for i in range(len(freshlist)):               # Append the keys        dictionary[freshlist[i]] = len(freshlist[i])              newlist = []         # Traverse the dictionary    for i in dictionary:         newlist.append(dictionary[i])             # Print the minimum of dictionary    return(min(newlist)) # Driver CodeS = "ababaabba"print(smallestSubstring(S))
<script> // JavaScript program for the above approach // Function to find the smallest// substring occurring only oncefunction smallestSubstring(a){    // Stores all occurrences    let a1 = [];      // Generate all the substrings    for(let i = 0; i < a.length; i++)    {        for(let j = i + 1; j <= a.length; j++)        {                          // Avoid multiple occurrences            if (i != j)                              // Append all substrings                a1.push(a.substring(i, j));        }    }      // Take into account    // all the substrings    let a2 = new Map();    for(let s=0;s<a1.length;s++)    {        if(a2.has(a1[s]))            a2.set(a1[s],a2.get(a1[s])+1);        else            a2.set(a1[s],1);    }      let freshlist = [];      // Iterate over all    // unique substrings    for(let s of a2.keys())    {                  // If frequency is 1        if (a2.get(s) == 1)              // Append into fresh list            freshlist.push(s);    }          // Initialize a dictionary    let dictionary = new Map();          for(let s=0;s<freshlist.length;s++)    {        // Append the keys        dictionary.set(freshlist[s],        freshlist[s].length);    }           let newlist = [];      // Traverse the dictionary    for(let s of dictionary.keys())        newlist.push(dictionary.get(s));      let ans = Number.MAX_VALUE;      for(let i=0;i<newlist.length;i++)        ans = Math.min(ans, newlist[i]);      // Return the minimum of dictionary    return ans == Number.MAX_VALUE ? 0 : ans;} // Driver Codelet S = "ababaabba";document.write(smallestSubstring(S));       // This code is contributed by unknown2108 </script>
2
 
Time Complexity: O(N2)Auxiliary Space: O(N2) 
mohit kumar 29
Kingash
unknown2108
anilk
sweetyty
frequency-counting
substring
Greedy
Hash
Searching
Sorting
Strings
Searching
Hash
Strings
Greedy
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Policemen catch thieves
K Centers Problem | Set 1 (Greedy Approximate Algorithm)
Number of indices pair such that element pair sum from first Array is greater than second Array
Minimize Cash Flow among a given set of friends who have borrowed money from each other
Maximize difference between the Sum of the two halves of the Array after removal of N elements
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum