Sherlock and Anagrams Hackerrank Solution
In this post we are going to discuss the Sherlock and Anagrams Hackerrank Solution in java.
Before looking at the problem statement and the solution lets see some terms that are needed for understanding the questions.
1.What are Anagrams?
- If the letters in one string can be rearranged to make the other string, then two strings are anagrams of each other.
- Assume that we have two strings, a="codi" and b="oicd".As you can see, both strings have the same amount of letters in each character
- {c-1,o-1,d-1,i-1} for a and {c-1,o-1,d-1,i-1} for b. As you can see, the characters in this instance are inverted, but the string's length and the total of its characters remain the same, making them both anagrams of one another.
- Consider the following: x:{w-1,e-1,b-1},y:{w-1,e-2,b-1}, where x="web" and y="webe".As you can see, the strings are not anagrams of one another because their lengths and total character counts differ.
The Problem statement is as follows:
Given a string, find the number of pairs of substrings of the string that are anagrams of each other.
Approach and Algorithm for Sherlock and Anagrams Hackerrank Solution:
- Finding the number of substrings that are anagrams of one another is the question's stated goal.
- Thus, we have two duties to complete. 1) Gather the String's Substrings. 2) Verify whether or not the substrings are anagrams.
- Java's inbuilt function substring(x,y) must be used to loop through the string and find each substring, with x and y representing the string's character indices, in order to find every substring.
- To determine whether two strings are anagrams of one another, note that anagrams have the same number of characters in both strings.
- Thus, we must count how often each character appears in the strings and then determine if the counts are the same or not. If they are, we return true; if not, we return false.
- In the end, we iterate over the substrings, determine whether they are anagrams, and increase the count if they are.
Check if Two String are anagrams in java:
public static boolean isanagram(String a, String b) {
if (a.length() != b.length()) return false;
int[] freq = new int[26];
for (int i = 0; i < a.length(); i++) {
freq[a.charAt(i) - 'a']++;
freq[b.charAt(i) - 'a']--;
}
for (int i: freq) {
if (i != 0) return false;
}
return true;
}
Please Let me Know, If you have any doubts.
Please Let me Know, If you have any doubts.