Check if a String is Isogram or Not
Problem​
Given a string S of lowercase alphabets, check if it is isogram or not. An Isogram is a string in which no letter occurs more than once.
Examples:​
Example 1:
Input:
S = machine
Output: 1
Explanation: machine is an isogram as no letter has appeared twice. Hence we print 1.
Example 2:
Input:
S = geeks
Output: 0
Explanation: geeks is not an isogram as 'e' appears twice. Hence we print 0.
Your task:​
This is a function problem. You only need to complete the function isIsogram() that takes a string as a parameter and returns either true or false.
- Expected Time Complexity:
- Expected Auxiliary Space: (Number of distinct characters)
Note: N = |S|
Constraints:​
Solution​
Python​
def isIsogram(self,s):
length = len(s)
mapHash = [0] * 26
for i in range(length):
mapHash[ord(s[i]) - ord('a')] += 1
if (mapHash[ord(s[i]) - ord('a')] > 1):
return False
return True
Java​
static boolean isIsogram(String data){
int length = data.length();
int[] mapHash = new int[26];
for (int i = 0; i < length; i++) {
char currentChar = data.charAt(i);
if (Character.isLetter(currentChar)) {
currentChar = Character.toLowerCase(currentChar);
mapHash[currentChar - 'a']++;
if (mapHash[currentChar - 'a'] > 1) {
return false;
}
}
}
return true;
}
C++​
bool isIsogram(string s) {
int length = s.length();
vector<int> mapHash(26, 0);
for (int i = 0; i < length; i++) {
char currentChar = s[i];
if (isalpha(currentChar)) {
currentChar = tolower(currentChar);
mapHash[currentChar - 'a']++;
if (mapHash[currentChar - 'a'] > 1) {
return false;
}
}
}
return true;
}
C​
int isIsogram(const char* s) {
int mapHash[26] = {0};
int length = 0;
const char* ptr = s;
while (*ptr != '\0') {
length++;
ptr++;
}
for (int i = 0; i < length; i++) {
char currentChar = s[i];
if (isalpha(currentChar)) {
currentChar = tolower(currentChar);
mapHash[currentChar - 'a']++;
if (mapHash[currentChar - 'a'] > 1) {
return 0;
}
}
}
return 1;
}
- Time Complexity:
- Auxiliary Space: (Number of distinct characters)