A classic interview question

elisabethgross

elisabethgross

Posted on February 5, 2020

A classic interview question

Hey everyone! Welcome back to Code Review, a series of coding interview challenges and career related content released weekly exclusively on Dev.to. I’m Elisabeth Gross and you might know me from the work I do on Coderbyte.com, a site dedicated to helping developers of any level get their next engineering job. Or, you may have heard of me via Breadwinnerss, a tool that helps users request intros for whichever roles they're interested in across dozens of companies. You might just be part of this awesome Dev.to community of passionate coders. Regardless of where you came from, welcome! If you like content like this - be sure to sign up for our newsletter here. Stand up’s over - lets get into the article!

The challenge

Given two strings, return true if they are anagrams of each other. Remember, an anagram is a word, phrase, or name formed by rearranging the letters of another, such as cinema, formed from iceman.

The less optimal approach

The sort function

This solution takes advantage of the built in sort function that comes with the javascript language. Many languages have a sort function but it’s important to know what the sort implementation is under the hood, especially when it comes to the overall time complexity of your algorithm. The V8 engine (the engine that powers the javascript that runs in the Chrome browser and Node.js) implements array sort using the MergeSort algorithm and has a time complexity of O(nlog(n)). It’s really important to demonstrate to your interviewer that you understand that using a built in method isn’t “free”, it’s just someone else’s code :)

The solution

Once you sort the strings, you can just compare them! If they are equal, they are anagrams. If they aren’t, return false. This is relatively straightforward in code.

function anagram(str1, str2) {

  // replace all whitespace in string, split into arrays, sort and rejoin as strings
  sorted1 = str1.toLowerCase().replace(/\s+/g, '').split('').sort().join()
  sorted2 = str2.toLowerCase().replace(/\s+/g, '').split('').sort().join()

  return sorted1 === sorted2
}

Try and come up with a more optimal solution for next week. Happy coding!

💖 💪 🙅 🚩
elisabethgross
elisabethgross

Posted on February 5, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related