We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
My Java 8 solution, which passes all test cases, with max score = 50:
The basic idea is as follows:
(1) Iterate through the entire string once, and for each new / distinct character encountered, accumulate the List of Indices where the character occurs into LinkedHashMap<Character, List<Integer>> chIdxMap.
(2) Iterate through all the Character Keys in LinkedHashMap<Character, List<Integer>> chIdxMap, and for each character: the Number of "Single Character Anagrams" (i.e. "aaa", "bbbb", etc) = (n * (n - 1)) / 2, where 'n' is the number of occurences of the character in the string.
(3) Iterate through the string again, and for each Character at each Index, start from "Anagram Length = 2", and search for all Anagrams of that Length. And keep incrementing Anagram Length by 1 at each iteration.
(Ignore the verbose debug print statements. Those were added to test the logic before submission, and have been commented out once solution was finalized & verified that everything passed).
classResult{publicstaticbooleanareAnagrams(Stringx,Stringy){// Early exit: lengths must match for anagramsif(x.length()!=y.length()){returnfalse;}// Frequency maps for both stringsMap<Character,Long>xFreq=x.chars().mapToObj(c->(char)c).collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));Map<Character,Long>yFreq=y.chars().mapToObj(c->(char)c).collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));returnxFreq.equals(yFreq);}publicstaticbooleancontainsOtherThanTarget(List<Integer>intLst,inttarget){returnintLst.stream().anyMatch(x->x!=target);}publicstaticList<Integer>findAllCharOccurrences(Stringinput,chartarget){List<Integer>indices=newArrayList<>();for(inti=0;i<input.length();i++){if(input.charAt(i)==target){indices.add(i);}}returnindices;}/* * Complete the 'sherlockAndAnagrams' function below. * * The function is expected to return an INTEGER. * The function accepts STRING s as parameter. */publicstaticintsherlockAndAnagrams(Strings){// Write your code hereintnumAnagramPairs=0;// System.err.println(""); System.err.println("");// System.err.println("s = >" + s + "<");LinkedHashMap<Character,List<Integer>>chIdxMap=newLinkedHashMap<>();for(intsIdx=0;sIdx<s.length();sIdx++){if(!chIdxMap.containsKey(s.charAt(sIdx))){chIdxMap.put(s.charAt(sIdx),findAllCharOccurrences(s,s.charAt(sIdx)));}}// System.err.println("chIdxMap = >" + chIdxMap + "<");for(CharacterchKey:chIdxMap.keySet()){List<Integer>curChIdxLst=chIdxMap.get(chKey);intn=curChIdxLst.size();intnumSingChAnag=(n*(n-1))/2;// System.err.println("chKey = >" + chKey + "< | curChIdxLst.size() = >" + // curChIdxLst.size() + "< | numSingChAnag = >" + // numSingChAnag + "<");numAnagramPairs+=numSingChAnag;}// System.err.println("After Single Char Anagram Pair Computation :: " + // "numAnagramPairs = >" + numAnagramPairs + "<");for(intsIdx=0;sIdx<s.length();sIdx++){List<Integer>curChIdxLst=chIdxMap.get(s.charAt(sIdx));// System.err.println("curChIdxLst = >" + curChIdxLst + "<");if(curChIdxLst.size()==1||!containsOtherThanTarget(curChIdxLst,sIdx)){continue;}for(intanaStrLen=2;(sIdx+anaStrLen)<=s.length();anaStrLen++){StringselSubStrSrc=s.substring(sIdx,sIdx+anaStrLen);// System.err.println("selSubStrSrc = >" + selSubStrSrc + "<" +// " from (" + sIdx + ", " + (sIdx + anaStrLen - 1) + ")");for(intcIdx=(sIdx+1);(cIdx+anaStrLen)<=s.length();cIdx++){StringselSubStrTgt=s.substring(cIdx,cIdx+anaStrLen);// System.err.println("selSubStrTgt = >" + selSubStrTgt + "<" +// " from (" + cIdx + ", " + (cIdx + anaStrLen - 1) + ")");if(areAnagrams(selSubStrSrc,selSubStrTgt)){// System.err.println("Anagram Found!");numAnagramPairs++;}}}}// System.err.println("numAnagramPairs = >" + numAnagramPairs + "<");returnnumAnagramPairs;}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Sherlock and Anagrams
You are viewing a single comment's thread. Return to all comments →
My Java 8 solution, which passes all test cases, with max score = 50:
The basic idea is as follows:
(1) Iterate through the entire string once, and for each new / distinct character encountered, accumulate the List of Indices where the character occurs into
LinkedHashMap<Character, List<Integer>> chIdxMap
.(2) Iterate through all the Character Keys in
LinkedHashMap<Character, List<Integer>> chIdxMap
, and for each character: the Number of "Single Character Anagrams" (i.e. "aaa", "bbbb", etc) = (n * (n - 1)) / 2, where 'n' is the number of occurences of the character in the string.(3) Iterate through the string again, and for each Character at each Index, start from "Anagram Length = 2", and search for all Anagrams of that Length. And keep incrementing Anagram Length by 1 at each iteration.
(Ignore the verbose debug print statements. Those were added to test the logic before submission, and have been commented out once solution was finalized & verified that everything passed).