Solve "Sherlock and Anagrams" coding challenge in JavaScript

### Photo by Javier Quesada on Unsplash

This post is going to get you through my solution of a coding challenge called "Sherlock and Anagrams". You may take a look at it in HackerRank. I spent a lot of time trying to solve it, with JavaScript. When I tried to google it, I could not find a decent JS solution. I found just one and it was not working correctly. Also any explanations were completely out of the question. That's why I decided to write an article about it and try to put some nice and easy to digest explanations along the way. Keep reading now!

⚠ CAUTION: I will roll out my solution below with short explanations about each of the steps. If you want to give a try yourself, please stop here and go to HackerRank site.

## Problem

Two strings are anagrams of each other if the letters of one string can be rearranged to form the other string. Given a string, find the number of pairs of substrings of the string that are anagrams of each other.

For example s = mom, the list of all anagrammatic pairs is [m, m], [mo, om] at positions [[0], [2]], [[0, 1], [1, 2]] respectively.

### Constraints

Length of the input string: 2 ≤ |s| ≤ 100

String s contains only lowercase letters from the range ascii[a-z].

## Analysis

First thing first - we need to get a better understanding of the whole problem. What is an anagram? What is an anagrammatic pair? Can I see one? Also, what exactly does it mean substrings?

In other words, we need to have a clear picture of what are we trying to solve, before solving it.

From the description of the problem we can deduct all we need. Keep walking! 🚶

I think here is a good moment to mention that the challenge in question is under "Dictionaries and Hashmaps" section in HackerRank website, so it's very likely for one to think, that probably he has to use this kind of data structures when solving it. 😇

### Anagrams

Since we are going to look for anagrams, let's start with them. As it is described above, an anagram of one word is another word, that has the same length and is created with the same characters from the former one.