IsIsogram alternative using simple bool array

It makes sense to use a map for this situation, but I actually came up with a different solution using a simple array of 26 bools. This solution takes advantage of the fact that under the hood, chars are integer values, and the letters ‘a’ to ‘z’ are represented as consecutive integers. Each bool in the array represents a letter, with index 0 as ‘a’, 1 as ‘b’, and so on. I calculate the index in the array by taking the letter and subtracting the value of ‘a’: ( ‘a’ - ‘a’ ) would equal 0, and since the lowercase letters are consecutive, ‘b’ is equal to ( ‘a’ + 1 ) and so on, getting all of our indices exactly where we want them.

bool FBullCowGame::IsIsogram( FString Word ) const
{
	// init array to all false
	bool LetterSeen[26] = { false };
	
	for ( char Letter : Word )
	{
		// calculate index from char value
		Letter = tolower( Letter );
		int32 LetterIndex = Letter - 'a';
		
		if ( LetterSeen[LetterIndex] ) return false;
		else LetterSeen[LetterIndex] = true;
	}

	return true;
}

I believe this method would be slightly better since it avoids the overhead of std::map, but like the instructor said earlier it really doesn’t matter much in this use case.

EDIT: I modified my code slightly, and wrapped the contents of the for loop with if ( isalpha( Letter ) ). This is necessary to avoid going outside the bounds of the array if we are passed a non-alphabetical character, which would give us an index outside of our 0-25 range.

3 Likes

Privacy & Terms