Skip to content

Commit 89b7ee4

Browse files
authored
Add one more solution for anagrams check (TheAlgorithms#4175)
1 parent bb830e9 commit 89b7ee4

2 files changed

Lines changed: 26 additions & 0 deletions

File tree

src/main/java/com/thealgorithms/strings/Anagrams.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@ public static void main(String[] args) {
4343
* Auxiliary Space Complexity : O(1)
4444
* 4th approach Time Complexity : O(n)
4545
* Auxiliary Space Complexity : O(n)
46+
* 5th approach Time Complexity: O(n)
47+
* Auxiliary Space Complexity: O(1)
4648
*/
4749
}
4850

@@ -122,4 +124,27 @@ boolean approach4(String s, String t) {
122124
return nm.equals(kk);
123125
}
124126
}
127+
128+
boolean approach5(String s, String t) {
129+
if(s.length() != t.length()){
130+
return false;
131+
}
132+
// Approach is different from above 4 aproaches.
133+
// Here we initialize an array of size 26 where each element corresponds to the frequency of a character.
134+
int[] freq = new int[26];
135+
// 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.
136+
for(int i=0; i<s.length(); i++){
137+
int pos1 = s.charAt(i) - 'a';
138+
int pos2 = s.charAt(i) - 'a';
139+
freq[pos1]++;
140+
freq[pos2]--;
141+
}
142+
// iterate through the frequency array and check if all the elements are zero, if so return true else false
143+
for(int i=0; i<26; i++){
144+
if(freq[i] != 0){
145+
return false;
146+
}
147+
}
148+
return true;
149+
}
125150
}

src/test/java/com/thealgorithms/strings/AnagramsTest.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,5 +18,6 @@ public void isAlphabetical() {
1818
assertTrue(anagrams.approach3(input1, "teal"));
1919
assertTrue(anagrams.approach4(input1, "tale"));
2020
assertTrue(anagrams.approach4(input1, "teal"));
21+
assertTrue(anagrams.approach5(input1, "teal"));
2122
}
2223
}

0 commit comments

Comments
 (0)