Check if a string contains an anagram of another string as its substring | Function to check if string s2 contains anagram of the string s1 as its substring ; Stores frequencies of characters in substrings of s2 ; Stores frequencies of characters in s1 ; If length of s2 exceeds length of s1 ; Store frequencies of characters in first substring of length s1len in string s2 ; Perform Sliding Window technique ; If hashmaps are found to be identical for any substring ; Driver Code
function checkAnagram ( s1 , s2 ) { var s2hash = Array ( 26 ) . fill ( 0 ) ; var s1hash = Array ( 26 ) . fill ( 0 ) ; var s1len = s1 . length ; var s2len = s2 . length ; if ( s1len > s2len ) return false ; var left = 0 , right = 0 ; while ( right < s1len ) { s1hash [ s1 [ right ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] += 1 ; s2hash [ s2 [ right ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] += 1 ; right ++ ; } right -= 1 ; while ( right < s2len ) { var ans = true ; for ( var i = 0 ; i < 26 ; i ++ ) { if ( s1hash [ i ] != s2hash [ i ] ) { ans = false ; } } if ( ans ) return true ; right ++ ; if ( right != s2len ) s2hash [ s2 [ right ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] += 1 ; s2hash [ s2 [ left ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] -= 1 ; left ++ ; } return false ; } var s1 = " " ; var s2 = " " ; if ( checkAnagram ( s1 , s2 ) ) document . write ( " " ) ; else document . write ( " " ) ;