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
isAnagram
takes two string inputss
andt
and returns a boolean value.The first line of the method checks if the length of
s
is not equal to the length oft
. If the lengths are not equal, the method returnsfalse
because anagrams must have the same length.The method creates two character arrays
sArr
andtArr
from the input stringss
andt
, 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 arrayssArr
andtArr
in alphabetical order. Sorting the arrays is necessary because anagrams have the same letters but may be in different orders.The sorted character arrays
sArr
andtArr
are then converted back into stringssNew
andtNew
using theString
constructor.Finally, the method returns
true
if the two stringssNew
andtNew
are 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
isAnagram
takes two string inputss
andt
and returns a boolean value.The first line of the method checks if the length of
s
is not equal to the length oft
. If the lengths are not equal, the method returnsfalse
because anagrams must have the same length.The method creates a
StringBuilder
objectt1
from the input stringt
. AStringBuilder
is a mutable sequence of characters that can be modified in place.The method loops through each character
ch
in the strings
using a for-each loop over thetoCharArray()
method ofs
.Inside the loop, the method checks if the string representation of the character
ch
is present int1
. If it is, the method removes the first occurrence of the characterch
fromt1
using thedeleteCharAt()
method ofStringBuilder
.After looping through all the characters in
s
, the method checks ift1
is empty by calling theisEmpty()
method ofStringBuilder
. Ift1
is empty, it means that all the characters int
that were also present ins
have been removed, sot
is 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
isAnagram
takes two string inputss
andt
and returns a boolean value.The first line of the method checks if the length of
s
is not equal to the length oft
. If the lengths are not equal, the method returnsfalse
because anagrams must have the same length.The method creates two empty
HashMap
objects,sMap
andtMap
, to store the frequency of each character in the stringss
andt
, respectively.The method loops through each character
ch
in the strings
using a for-each loop over thetoCharArray()
method ofs
.Inside the loop, the method retrieves the current value of the frequency of the character
ch
from thesMap
using thegetOrDefault()
method ofHashMap
. If the value is not equal to 0, it means that the characterch
has already been encountered ins
, so the method increments the value by 1. Otherwise, it means that the characterch
has not been encountered ins
yet, 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
ch
in the stringt
using 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
tMap
instead ofsMap
.After looping through both strings, the method checks if the
sMap
is equal totMap
using theequals()
method ofHashMap
. If the two maps are equal, it means that the frequency of each character ins
is the same as the frequency of each character int
, sot
is 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 HashMap
s, 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😁