Smallest substring occurring only once in a given string | C ++ program for the above approach ; Function to find the smallest substring occurring only once ; Stores all occurences ; Generate all the substrings ; Avoid multiple occurences ; Append all substrings ; Take into account all the substrings ; Iterate over all unique substrings ; If frequency is 1 ; Append into fresh list ; Initialize a dictionary ; Append the keys ; Traverse the dictionary ; Print the minimum of dictionary ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int smallestSubstring ( string a ) { vector < string > a1 ; for ( int i = 0 ; i < a . size ( ) ; i ++ ) { for ( int j = i + 1 ; j < a . size ( ) ; j ++ ) { if ( i != j ) a1 . push_back ( a . substr ( i , j + 1 ) ) ; } } map < string , int > a2 ; for ( string i : a1 ) a2 [ i ] ++ ; vector < string > freshlist ; for ( auto i : a2 ) { if ( i . second == 1 ) freshlist . push_back ( i . first ) ; } map < string , int > dictionary ; for ( auto i : freshlist ) { dictionary [ i ] = i . size ( ) ; } vector < int > newlist ; for ( auto i : dictionary ) newlist . push_back ( i . second ) ; int ans = INT_MAX ; for ( int i : newlist ) ans = min ( ans , i ) ; return ans ; } int main ( ) { string S = " ababaabba " ; cout << smallestSubstring ( S ) ; return 0 ; }