Loading...
New webinar: "The Remote Job Search: My Microverse Journey" with graduate Paul Rail
Watch Now

In this article, we will work through this problem from HackerRank. As we solve this problem you will learn all about how to implement an anagram with JavaScript.

What Are Anagrams and How Do We Apply Them to Strings?

Anagrams are two words or phrases that can be rearranged to form another word or phrase. An example of an anagram is using the phrase, "elegant man" to form the phrase "a gentleman". 

Here’s a problem to help you understand this concept in JavaScript

While in the world of coding, a task you might be asked to perform is an operation with Strings. You’ll need to figure out the least amount of characters that can be swapped within a string, in order to make two substrings an anagram of each other.

Consider this example; 

You have a string “abddfg”. So, you would split this into two parts like “abd” and “dfg” .

Now, let’s have a look at the features of this split since they are important to understand. 

Firstly, all the letters have been used. Secondly, the divided substrings are of equal lengths and lastly they are contiguous too. You make further changes as you wish, for example changing “b” and “d” from the first subscript to “f” and “g”.The criteria is to make a minimum of 2 changes for an anagram to be formed.

Considering all of this, you need to complete the anagram function. Also, make sure that it returns to the least possible characters required to make anagrams. If the anagram is not possible it should display “-1”.

Constraints:

The following are the constraints for these problems:

  • 1≤q≤100
  • 1≤≤10^4

So the query can go up to 100, and the string length can be up to 10^4, which means that the length is pretty reasonable.

Example:

In this example, there are 6 queries and 6 strings:

1. For the first query, you need to break the given characters into two parts, “aaa” and “bbb”. As a matter of fact, if you need to make changes to either of the characters, you’ll actually have to change three characters, and hence, the result displayed in the output section is “3”.

2. In the case of “ab”, changes will have to be incurred with one character only.

3. The case of “abc” is a rather interesting case and in fact, you can’t form an anagram in such cases. This is because in order to make an anagram, you have to break it into two parts and if you do so, one string will have an extra character than the other. So, you cannot do anything in such cases and as is visible in the output displayed, the result of such cases are displayed as “-1” showing no anagram.

4. In the fourth query, you will need to break it into two characters thus, it’s displayed as 2. 

5. In the fifth query, it is not possible to make an anagram so the output is 0.

6.The sixth query is a tricky one. This is because they are basically the same letters so changing the arrangement and orientation won’t make a difference.

7. In the final query, you will only need to change one letter and you will be good to go.

Splitting up Strings

Consider the following example where you will break off a string into two substrings. Here we choose one variable to represent the subscripts of both the substrings. 

You may use the following code:

{% code-block language="js" %}
function anagram(s) {
    let midOfString = Math.floor(s.length / 2);
    let firstHalf = s.substring(0, midOfString);
    let secondHalf = s.substring(midOfString);
    let count = 0;
}
{% code-block-end %}

Checking the Length of the String

For the strings to match, there must be length compatibility so  you must check the lengths. If the lengths don’t match, anagrams can’t be formed.

Applying Conditional Statements

Since the length is so important in making anagrams, you will have to implement conditional statements. 

For example:

{% code-block language="js" %}
    if (s.length % 2 !== 0) {
        return -1;
}
{% code-block-end %}

Here we applied the condition of whether the initial string can be divided by two or not. In this case, if it isn’t divisible by two, the anagrams won’t be formed since the substrings won’t be equal. Thus, in the output it will display as “-1”.

Looping through a For Loop

In the event the letter you were supposed to replace in the ongoing index is present in the second half substring, you will have to go with JavaScript’s built-in replace() method. This is because by doing so, your problem letter will automatically be skipped and removed. When you add empty quotes in the parameter, the current character will automatically be removed.

In the event that the letters are not in the second half, you will see an additional increase by one in the count variable. The reason behind this is that such a change is required to form an anagram.

Here’s how it’s done:

{% code-block language="js" %}
function anagram(s) {
    let midOfString = Math.floor(s.length / 2);
    let firstHalf = s.substring(0, midOfString);
    let secondHalf = s.substring(midOfString);
    let count = 0;
    if (s.length % 2 !== 0) {
        return -1;
    }
    for (let i = 0; i < firstHalf.length; i++) {
        secondHalf.includes(firstHalf[i]) ? 
        secondHalf = secondHalf.replace(firstHalf[i],"") : count++;
    }
    return count;}
{% code-block-end %}

You can also view the video tutorial of this concept below.

https://youtu.be/7ss-Es-MIJI

Conclusion

After reviewing this article you should now know how to implement an anagram with JavaScript. Once you understand it fully, most of your queries on this topic, such as; Checking the Length of the String, Applying Conditional Statements, Looping through the First Half Substring, and others will be easier to undestand. Best of luck implementing anagrams with JavaScript, and happy coding! 

Subscribe to our Newsletter

Get Our Insights in Your Inbox

Career advice, the latest coding trends and languages, and insights on how to land a remote job in tech, straight to your inbox.

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.