Sherlock and Anagrams Optimization
Your problem is not in the code, but in your algorithm. Brute-forcing the solution as you are doing is fundamentally slow, and you need to tackle the problem from a different angle if you want to make a substantial dent in your runtime.

The problem is constrained in two specific ways we can exploit:


Only letters in the 'a'->'z' range are admissible. That's only 26 letters.
Only strings of length &lt;= 100 characters are admissible. By extension, this means we'll never have more than 100 substrings of a given length to deal with.


Now, if I had a function that converts a substring into "some" representation that's common between annagrammic pairs, but only between annagrammic pairs, I could simply generate that representation for each substring and work off that datastructure instead (probably by using it as a key to a map of number of instances seen).

Since we only have 26 possible letters, a simple std::array&lt;uint8_t, 26&gt;, where each cell represents the number of times a given letter appears in the substring, has all the properties we need.

Just to make sure I'm not spouting nonsense, I gave it a try, and my solution using these principles solves all the hackerrank test cases in under 10ms. 

I encourage you to give it a try by yourself, but if you request it, I'll be glad to post the code for my solution here.