Grind 75 Question 7: Valid Anagram
Since I’m a glutton for punishment, I’m peeking at this one at 9:11 p.m.
The Question
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.
The First Attempts
var isAnagram = function(s, t) {
if(s.sort() === t.sort()) {
return true;
}
return false;
};
I know it cannot possibly be this easy, but I truly whiteboarded it as if I was in a Google interview. I also know there’s a way to sort in Javascript, but it might involve turning the strings into arrays. Now to actually run the code, find out I’m horribly wrong, and then try, try again.
I quickly, beautifully turn my strings into sorted arrays and then discover, to my horror, that arrays can’t be compared. So I have two options. First, I can turn the sorted arrays back into strings and compare them. I believe that’s called “brute force”. Second, I can figure out a more graceful approach, which might involve splicing and/or popping…
The Solution
var isAnagram = function(s, t) {
const sArray = s.split('');
const tArray = t.split('');
const sArraySorted = sArray.sort();
const tArraySorted = tArray.sort();
if(sArraySorted.toString() === tArraySorted.toString()) {
return true;
}
return false;
};
My brute force works! It is 9:25 pm as I am typing these words, meaning that I am one minute short of the estimated 15 minutes it would take to do this problem! And yet. I am unsatisfied. I have to do it more prettily.
…
More prettily ends up not working. Jarrod gets home from work around 9:45 and finds me still working on splicing and dicing. I shut my computer down for the night. The next morning I get a bit further, but the approach I’m trying is still not working, so I decide that it’s time to officially move on.
In any case, would my second attempt really have been much more efficient? The approach was to turn s and t into arrays and splice out the matching letters, hopefully ending up with empty arrays. But having to search arrays over and over again seems to be…not a great solution. I’ll Neetcode this one and move on.
What I Learned
- Arrays can’t be compared against each other! Darn.
- Got more practice with Array.sort()
mins
read