Smallest substring occurring only once in a given string Last Updated : 10 Jan, 2023 Comments Improve Suggest changes Like Article Like Report 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++ // C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to find the smallest // substring occurring only once int 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 Code int main() { string S = "ababaabba"; cout<<smallestSubstring(S); return 0; } // This code is contributed by mohit kumar 29. Java // Java program for the above approach import java.io.*; import java.lang.*; import java.util.*; class GFG{ // Function to find the smallest // substring occurring only once static 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 Code public static void main(String[] args) { String S = "ababaabba"; System.out.println(smallestSubstring(S)); } } // This code is contributed by Kingash Python3 # Python3 program of the above approach from collections import Counter # Function to find the smallest # substring occurring only once def 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 Code S = "ababaabba" print(smallestSubstring(S)) C# using System; using System.Collections.Generic; using System.Linq; class GFG { // Function to find the smallest // substring occurring only once static int SmallestSubstring(string a) { // Stores all occurrences var a1 = new List<string>(); // 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 - i)); } } // Take into account // all the substrings var a2 = new Dictionary<string, int>(); foreach (string s in a1) if (a2.ContainsKey(s)) a2[s]++; else a2[s] = 1; var freshlist = new List<string>(); // Iterate over all // unique substrings foreach (string s in a2.Keys) { // If frequency is 1 if (a2[s] == 1) // Append into fresh list freshlist.Add(s); } // Initialize a dictionary var dictionary = new Dictionary<string, int>(); foreach (string s in freshlist) { // Append the keys dictionary[s] = s.Length; } var newlist = new List<int>(); // Traverse the dictionary foreach (string s in dictionary.Keys) newlist.Add(dictionary[s]); int ans = int.MaxValue; foreach (int i in newlist) ans = Math.Min(ans, i); // Return the minimum of dictionary return ans == int.MaxValue ? 0 : ans; } // Driver Code static void Main(string[] args) { string S = "ababaabba"; Console.WriteLine(SmallestSubstring(S)); } } // This code is contributed by phasing17 JavaScript <script> // JavaScript program for the above approach // Function to find the smallest // substring occurring only once function 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 Code let S = "ababaabba"; document.write(smallestSubstring(S)); // This code is contributed by unknown2108 </script> Output: 2 Time Complexity: O(N2)Auxiliary Space: O(N2) Comment More infoAdvertise with us Next Article Smallest substring occurring only once in a given string saikumarkudikala Follow Improve Article Tags : Strings Greedy Searching Sorting Hash DSA frequency-counting substring +4 More Practice Tags : GreedyHashSearchingSortingStrings +1 More Similar Reads DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on 7 min read Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s 12 min read Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge 14 min read Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir 8 min read Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st 2 min read Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta 15+ min read Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc 15 min read Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T 9 min read Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example 12 min read Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an 8 min read Like