Saturday, September 16, 2023

 Check if two Strings are anagrams


An anagram of a string is another string that contains the same characters, only the order of characters can be different.
For example, string "stri" and string "rits" are anagrams, because they are of the same length and contain the same characters.

There are a few ways we can check if a string is anagram of another string in Java:


Using sorting

We can just sort both strings and compare them. We just first need to convert them to arrays.

public boolean isAnagram(String str1, String str2) {

if (str1.length() != str2.length()) {
return false;
}

String[] strArray1 = str1.split("");
String[] strArray2 = str2.split("");

Arrays.sort(strArray1);
Arrays.sort(strArray2);

return Arrays.equals(strArray1, strArray2);
}

The time complexity of this solution is O(n log n) since the Arrays.sort() method uses a quick sort algorithm to sort the array.
The space complexity is O(n) since we are creating two new arrays.


With a StringBuilder and removal of characters

We can convert the str2 into a StringBuilder and then iterate over the str1 and remove the character by character from the StringBuilder.
If the length of the string that is held by StringBuilder is 0, it means the strings are anagrams of each other.

public boolean isAnagram(String str1, String str2) {

if (str1.length() != str2.length()) {
return false;
}

StringBuilder stringBuilder2 = new StringBuilder(str2);

for (int i = 0; i < str1.length(); i++) {
int index = stringBuilder2.indexOf(String.valueOf(str1.charAt(i)));

if (index != -1) {
stringBuilder2.deleteCharAt(index);
} else {
return false;
}
}

return stringBuilder2.length() == 0;
}

The time complexity of this solution is O(n) since we are iterating through the array and visiting each element.
For the space complexity, it uses a little extra memory, since we are creating a new StringBuilder object which has a number of elements the same as the arrays, but we remove each char per iteration, so the memory consumption is getting smaller and smaller.




No comments:

Post a Comment