Problem
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
Constraints:
1 <= s.length, t.length <= 5 * 104
s
andt
consist of lowercase English letters.
Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
Solution
First attempt : (Non optimized)
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isAnagram = function(s, t) {
const sset = s.split("");
const tset = t.split("");
if(s.length == t.length){
for(let i = 0 ; i < sset.length; i++){
let value =sset[i];
if(tset.includes(value)){
let index = tset.indexOf(value);
tset.splice(index,1)
}
else{
return false;
}
}
}
else{
return false;
}
return true
};
After giving it a second attempt I tried optimizing it further and here is what I have done so far :
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isAnagram = function(s, t) {
let ss = s.split("");
let tt = t.split("");
const dict = {}
if(s.length == t.length){
for(let i = 0 ; i < ss.length; i++){
if(dict[ss[i]]){
dict[ss[i]]++;
}
else{
dict[ss[i]] = 1;
}
}
for(let y = 0 ; y < tt.length; y++){
if(dict[tt[y]]){
dict[tt[y]]--;
}
else{
return false;
}
}
}
else{
return false;
}
return true
};
A freelance web developer with a decade of experience in creating high-quality, scalable web solutions. His expertise spans PHP, WordPress, Node.js, MySQL, MongoDB, and e-commerce development, ensuring a versatile approach to each project. Aadi’s commitment to client satisfaction is evident in his track record of over 200 successful projects, marked by innovation, efficiency, and a customer-centric philosophy.
As a professional who values collaboration and open communication, Aadi has built a reputation for delivering projects that exceed expectations while adhering to time and budget constraints. His proactive and problem-solving mindset makes him an ideal partner for anyone looking to navigate the digital landscape with a reliable and skilled developer.