Checking if a string is an isogram →
A string is an isogram if no character in it appears more than once.
Let us write a simple algorithm to identify if a given input string is an isogram. For simplicity let us consider only strings that have small characters and no spaces or special characters i.e. - only characters from a to z.
In our previous post, we learnt how to keep track of characters that appear in a string as we traverse the input string. We use the same idea here, just this time we simplify it to be 26 characters (a to z) instead of 256.
- We traverse the input string and maintain a counter for each of the occurences in the string. Note that we subtract ‘a’ from the ASCII value as our strings contain only a to z and we want our index
0
to correspond to a. The intention of this simplification was precisely to learn how to modify our algorithm for such specific use cases. - We traverse the counter array (which is essentially a mapping
seen: character -> count
to see if any of the characters appeared more than once (i.e. their count mapping is greater than 1).