Given a string S of lowercase characters. The task is to check whether a given string is a Heterogram or not using Python. A heterogram is a word, phrase, or sentence in which no letter of the alphabet occurs more than once.
Input1: S = "the big dwarf only jumps"
Output1: Yes
Explanation: Each alphabet in the string S is occurred only once.
Input2: S = "neveropen"
Output2: No
Explanation: Since alphabet 'g', 'e', 'k', 's' occurred more than once.
We have an existing solution for this problem. Please refer to Check whether a given string is a Heterogram or not link. Some other solutions for this problem are given below.
Python program to check whether a given string is Heterogram or not
Below are the approaches using which we can check whether a given string is Heterogram or not:
Check Whether a Given String is Heterogram using Set
The approach is to check sentence is a heterogram or not. We are only concerned about the alphabet, not any other character, so we separate out the list of all alphabets present in the sentence. We convert a list of alphabets into a set because the set contains unique values, if the length of the set is equal to the number of alphabets that means each alphabet occurred once then the sentence is a heterogram, otherwise not.
Python3
# Function to Check whether a given string is Heterogram or not def heterogram( input ): # separate out list of alphabets using list comprehension # ord function returns ascii value of character alphabets = [ch for ch in input if ( ord (ch) > = ord ( 'a' ) and ord (ch) < = ord ( 'z' ))] # convert list of alphabets into set and # compare lengths if len ( set (alphabets)) = = len (alphabets): print ( 'Yes' ) else : print ( 'No' ) # Driver program if __name__ = = "__main__" : input = 'the big dwarf only jumps' heterogram( input ) |
Output:
Yes
Check Whether a Given String is Heterogram using lower()+isalpha()
In this approach, we sorts the input string in lowercase and then checks if any consecutive characters are equal and alphabetical. If such characters exist, then the function returns False, else it returns True, indicating that the input string is a heterogram.
Python3
def is_heterogram(string): sorted_string = sorted (string.lower()) for i in range ( 1 , len (sorted_string)): if sorted_string[i] = = sorted_string[i - 1 ] and sorted_string[i].isalpha(): return 'No' return 'Yes' string = 'the big dwarf only jumps' print (is_heterogram(string)) |
Yes
Time Complexity: O(nlogn), where n is the length of the input string.
Auxiliary Space: O(n), where n is the length of the input string.