Lecture 45 O(n) runtime

you can create an array with a size of all the possible letters (u will need to have a new const variable with the number of possible characters - in case u want other characters or uppercase letters as well for example)

the array will be of type int (we will fill it with the default value of 0)

u go over all the letters in the guess and for each letter u got to its appropriate cell in the array
(how do u do it? u can go do something like array[letter - ‘a’] - the abc letters are arranged according to the ASCII chart one after another so ‘a’ would go to the 0 location in the array and for example ‘p’ would go to the 15th location in the array)
in that location u can check if the letter was already sighted or not according to the value there (0 = not sighted, 1 = sighted once)
if its 0 u change it to 1
otherwise you report that the word is not an isogram

all in all u have to go over the array only once so its O(n)
the downside is the memory loss for the array we created - if we have to be cheap on memory we should go for the sort and than check option ( O(n*logn) )

** as a side note it might have been better to make the array of bool or enum type (would have been a better looking code) but if the game rules changes and someone wants to create a game where u can have 1/2/3 or x repetitions of the same letter allowed - it will require much less changes with an int array than a bool/enum array (in int u can count the number of letter sightings till it reaches the max number allowed)

Privacy & Terms