The Wayback Machine - https://web.archive.org/web/20210304202717/https://www.geeksforgeeks.org/smallest-substring-occurring-only-once-in-a-given-string/
Skip to content
Related Articles

Related Articles

Smallest substring occurring only once in a given string
  • Last Updated : 04 Mar, 2021

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: 2
Explanation: 
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:

Python3




# Python program of the above approach
from collections import Counter
  
# Function to find the smallest
# substring occurring only once
def smallestSubstring(a):
    
    # Stores all occurences
    a1 = []  
      
    # Generate all the substrings
    for i in range(len(a)):
        for j in range(i+1, len(a)):
            
            # Avoid multiple occurences
            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))


Output:

2

Time Complexity: O(N2)
Auxiliary Space: O(N2)

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :