So I've recently been researching all there is to do with run-time complexity of algorithms and wanting to learn how to alter them to improve efficiency for when the scale of n is increased, so essentially my aim is to learn how to make things O (log n). Thought to myself, I know of a good little project I could do this hour and thats create an anagram checker.
I rummaged through a few SO posts and saw someone commented it could be made log n if you assigned every letter in the alphabet to a numeric thus:
final Map<Character, Integer> map;
String str = "hello";
String check = "olleh";
map = new HashMap<>();
map.put('a', 2);
map.put('b', 3);
map.put('c', 4);
map.put('d', 7);
map.put('e', 11);
map.put('f', 13);
map.put('g', 17);
map.put('h', 19);
map.put('i', 23);
map.put('j', 29);
map.put('k', 31);
map.put('l', 37);
map.put('m', 41);
map.put('n', 43);
map.put('o', 47);
map.put('p', 53);
map.put('q', 59);
map.put('r', 61);
map.put('s', 67);
map.put('t', 71);
map.put('u', 73);
map.put('v', 79);
map.put('w', 83);
map.put('x', 89);
map.put('y', 97);
map.put('z', 101);
Then I created the method:
public static boolean isAnagram(String s, String check,Map<Character, Integer> map) {
int stringTotal = 0;
int checkTotal = 0;
for(char ch: s.toCharArray()){
int i = map.get(ch);
stringTotal += ch;
}
for(char ch: check.toCharArray()){
int i = map.get(ch);
checkTotal +=ch;
}
if (stringTotal == checkTotal){
return true;
}
return false;
}
I believe that this method is O(n^2) because it has two independent loops, I cannot think of the logic behind creating this to a O(log n) method.
Any pointers would be great