diff --git a/src/main/java/com/thealgorithms/strings/Anagrams.java b/src/main/java/com/thealgorithms/strings/Anagrams.java index 5a9487da..33ea900e 100644 --- a/src/main/java/com/thealgorithms/strings/Anagrams.java +++ b/src/main/java/com/thealgorithms/strings/Anagrams.java @@ -43,6 +43,8 @@ public class Anagrams { * Auxiliary Space Complexity : O(1) * 4th approach Time Complexity : O(n) * Auxiliary Space Complexity : O(n) + * 5th approach Time Complexity: O(n) + * Auxiliary Space Complexity: O(1) */ } @@ -122,4 +124,27 @@ public class Anagrams { return nm.equals(kk); } } + + boolean approach5(String s, String t) { + if(s.length() != t.length()){ + return false; + } + // Approach is different from above 4 aproaches. + // Here we initialize an array of size 26 where each element corresponds to the frequency of a character. + int[] freq = new int[26]; + // iterate through both strings, incrementing the frequency of each character in the first string and decrementing the frequency of each character in the second string. + for(int i=0; i