Given a string, find minimum number of changes to it so that all substrings of the string become distinct.
Input : str = "aab" Output : 1 If we change one instance of 'a' to any character from 'c' to 'z', we get all distinct substrings. Input : str = "aa" Output : 1
To make all substrings distinct, every character must be different. So we simply need to count number of repeated characters. If length of string is more than 26, then we cannot convert it into a string with all distinct substrings (Here we assume that string should contain only lower case characters, ‘a’ to ‘z’)
# Python3 program to count number of changes
# to make all substrings distinct.
MAX_CHAR = 
# Returns minimum changes to str so
# that no substring is repeated.
n = len(str )
# If length is more than maximum
# allowed characters, we cannot
# get the required string.
if (n > MAX_CHAR):
# Variable to store count of
# distinct characters
dist_count = 0
# To store counts of different
count =  * MAX_CHAR
for i in range(n):
if (count[ord(str[i]) – ord(‘a’)] == 0) :
dist_count += 1
count[(ord(str[i]) – ord(‘a’))] += 1
# Answer is, n – number of distinct char
return (n – dist_count)
# Driver Code
if __name__ == ‘__main__’:
str = “aebaecedabbee”
# This code is contributed
# by SHUBHAMSINGH10
- Find distinct characters in distinct substrings of a string
- Count of distinct substrings of a string using Suffix Array
- Count of distinct substrings of a string using Suffix Trie
- Minimum steps to delete a string after repeated deletion of palindrome substrings
- Minimum changes required to make first string substring of second string
- Minimum number of deletions to make a string palindrome | Set 2
- Minimum cost to make a string free of a subsequence
- Minimum number of deletions to make a string palindrome
- Minimum number of replacements to make the binary string alternating | Set 2
- Minimum swaps required to make a binary string alternating
- Minimum characters to be added at front to make string palindrome
- Minimum number of Appends needed to make a string palindrome
- Minimum replacements to make adjacent characters unequal in a ternary string
- Minimum number of characters to be removed to make a binary string alternate
- Minimum replacements to make adjacent characters unequal in a ternary string | Set-2
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.