From 89b7ee42e6010323e4b4c0556c3005620f1d9845 Mon Sep 17 00:00:00 2001 From: Manoj Kumar <52065298+manojCode94@users.noreply.github.com> Date: Fri, 5 May 2023 23:20:47 +0530 Subject: [PATCH] Add one more solution for anagrams check (#4175) --- .../com/thealgorithms/strings/Anagrams.java | 25 +++++++++++++++++++ .../thealgorithms/strings/AnagramsTest.java | 1 + 2 files changed, 26 insertions(+) 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