An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.
Example:
is_isogram("Dermatoglyphics" ) == true
is_isogram("aba" ) == false
is_isogram("moOse" ) == false # -- ignore letter case
This challenge comes from chunjef on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (15)
Here’s my JS implementation using .reduce() :) :
Hindsight, @savagepixie ’s answer using sets was much better and more efficient! Set theory is always better in situations like this :)
To be fair,
Set
usually isn't my first thought when solving problems. It's one of those things I kinda know are there but don't use that often.In php it can be done like this:
I dropped some lines in Typescript.
Solution based on filter() and indexOf. indexOf returns the index of the first occurrence of the item in the array. So if a character appears the second time in the string, indexOf and index will be different.
Python solution 🐍
Haskell
I think the complexity of this method is O(n2), but it shouldn't matter too much since the since
&&
can exit early, so the maximum number of iterations can only be 26 (by the pigeonhole principle).In Go.
JavaScript
I think.
Use 2 pointers i, j. i runs from left side of string and j runs from right side of string.
We will compare each element on left side with right size if equal we will return false the if not equal increase i and decrease j then continue compare. I came up with idea when i read the problem
I might be wrong, but if you try with the word
abcb
which is not a word but just for the simplicity of the explanation, it would fail to find it using two pointers.You have, in my understanding, no other choice but to check every letters for each letter pass, which make the worst case an O(n²) complexity. And I think the best case scenario for the complexity could be O(1) when the same letter is repeated twice in a row.
Here is what the algorithm could look like in JavaScript.
So probably we can put all characters into Set then compare number of count. That is might be good solution.
in PHP
Thanks for the suggestion.
Edited the solution.
Nice. Just the kind of "essential" solution I like.