Lets Code Everyday - Day 25

Question - 25:
Valid Anagram
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
First approach:
class Solution {
public boolean isAnagram(String s, String t) {
if(s.length()!=t.length()) return false;
char[] sArr= s.toCharArray();
char[] tArr= t.toCharArray();
Arrays.sort(sArr);
Arrays.sort(tArr);
String sNew= new String(sArr);
String tNew= new String(tArr);
return sNew.equals(tNew);
}
}
Step-by-step implementation:
The method
isAnagramtakes two string inputssandtand returns a boolean value.The first line of the method checks if the length of
sis not equal to the length oft. If the lengths are not equal, the method returnsfalsebecause anagrams must have the same length.The method creates two character arrays
sArrandtArrfrom the input stringssandt, respectively. A character array is an array of characters that can be manipulated using various built-in methods.The
Arrays.sort()method is used to sort the character arrayssArrandtArrin alphabetical order. Sorting the arrays is necessary because anagrams have the same letters but may be in different orders.The sorted character arrays
sArrandtArrare then converted back into stringssNewandtNewusing theStringconstructor.Finally, the method returns
trueif the two stringssNewandtNeware equal, which means they contain the same characters in the same order. Otherwise, the method returnsfalse.
In summary, this method determines if two strings are anagrams of each other by checking if they have the same length, sorting their characters alphabetically, and comparing the sorted strings to see if they are equal.
The time complexity of the given code is O(n log n), where n is the length of the input strings, due to the sorting algorithm used, and the space complexity is O(n) because the method creates two character arrays of size n and two string objects of size n.
Second approach:
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
StringBuilder t1 = new StringBuilder(t);
for (char ch : s.toCharArray()) {
if (t1.toString().contains(ch + "")) {
t1.deleteCharAt(t1.indexOf(ch + ""));
}
}
return t1.toString().isEmpty();
}
}
Step-by-step implementation:
The method
isAnagramtakes two string inputssandtand returns a boolean value.The first line of the method checks if the length of
sis not equal to the length oft. If the lengths are not equal, the method returnsfalsebecause anagrams must have the same length.The method creates a
StringBuilderobjectt1from the input stringt. AStringBuilderis a mutable sequence of characters that can be modified in place.The method loops through each character
chin the stringsusing a for-each loop over thetoCharArray()method ofs.Inside the loop, the method checks if the string representation of the character
chis present int1. If it is, the method removes the first occurrence of the characterchfromt1using thedeleteCharAt()method ofStringBuilder.After looping through all the characters in
s, the method checks ift1is empty by calling theisEmpty()method ofStringBuilder. Ift1is empty, it means that all the characters intthat were also present inshave been removed, sotis an anagram ofs, and the method returnstrue. Otherwise, the method returnsfalse.
In summary, this method determines if two strings are anagrams of each other by checking if they have the same length, looping through the characters in one string and removing them from the other string using a StringBuilder, and checking if the resulting StringBuilder is empty.
The time complexity of the given code is O(n^2), where n is the length of the input strings, due to the nested loop and the indexOf() method used inside the loop, and the space complexity is O(n) because the method creates a StringBuilder object of size n.
Third approach:
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
Map<Character, Integer> sMap = new HashMap<>();
Map<Character, Integer> tMap = new HashMap<>();
for (char ch : s.toCharArray()) {
int val = sMap.getOrDefault(ch, 0);
if (val != 0) val++;
else val = 1;
sMap.put(ch, val);
}
for (char ch : t.toCharArray()) {
int val = tMap.getOrDefault(ch, 0);
if (val != 0) val++;
else val = 1;
tMap.put(ch, val);
}
return sMap.equals(tMap);
}
}
Step-by-step implementation:
The method
isAnagramtakes two string inputssandtand returns a boolean value.The first line of the method checks if the length of
sis not equal to the length oft. If the lengths are not equal, the method returnsfalsebecause anagrams must have the same length.The method creates two empty
HashMapobjects,sMapandtMap, to store the frequency of each character in the stringssandt, respectively.The method loops through each character
chin the stringsusing a for-each loop over thetoCharArray()method ofs.Inside the loop, the method retrieves the current value of the frequency of the character
chfrom thesMapusing thegetOrDefault()method ofHashMap. If the value is not equal to 0, it means that the characterchhas already been encountered ins, so the method increments the value by 1. Otherwise, it means that the characterchhas not been encountered insyet, so the method sets the value to 1. The method then puts the key-value pair(ch, val)in thesMap.The method then loops through each character
chin the stringtusing a for-each loop over thetoCharArray()method oft.Inside the second loop, the method performs the same operations as in the first loop, but with the
tMapinstead ofsMap.After looping through both strings, the method checks if the
sMapis equal totMapusing theequals()method ofHashMap. If the two maps are equal, it means that the frequency of each character insis the same as the frequency of each character int, sotis an anagram ofs, and the method returnstrue. Otherwise, the method returnsfalse.
In summary, this method determines if two strings are anagrams of each other by counting the frequency of each character in both strings using HashMaps, and then comparing the two maps.
This implementation has a time complexity of O(n), where n is the length of the input strings, because it loops through each character in both strings once, and the getOrDefault() and put() methods of HashMap have a time complexity of O(1). The space complexity of this implementation is also O(n) because the method creates two HashMap objects of size n.
Conclusion:
In terms of time complexity third approach is better i.e., O(n) compared to the first and the second approaches i.e., O(n logn) & O(n^2)
Thanks for reading ....Happy Learning😁




