Difference between maximum and minimum of a set of anagrams from an array | C ++ program for the above approach ; Utility function to find the hash value for each element of the given array ; Initialize an array with first 10 prime numbers ; Iterate over digits of N ; Update Hash Value ; Update N ; Function to find the set of anagrams in the array and print the difference between the maximum and minimum of these numbers ; Map to store the hash value and the array elements having that hash value ; Find the hash value for each arr [ i ] by calling hash function ; Iterate over the map ; If size of vector at m [ i ] greater than 1 then it must contain the anagrams ; Find the minimum and maximum element of this anagrams vector ; Display the difference ; If the end of Map is reached , then no anagrams are present ; Driver Code ; Given array ; Size of the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; int hashFunction ( int N ) { int prime [ 10 ] = { 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 } ; int value = 1 , r ; while ( N != 0 ) { r = N % 10 ; value = value * prime [ r ] ; N = N / 10 ; } return value ; } void findDiff ( int arr [ ] , int n ) { map < int , vector < int > > m ; int h , min , max ; for ( int i = 0 ; i < n ; i ++ ) { h = hashFunction ( arr [ i ] ) ; m [ h ] . push_back ( arr [ i ] ) ; } for ( auto i = 0 ; i != m . size ( ) ; i ++ ) { if ( m [ i ] . size ( ) > 1 ) { min = * min_element ( m [ i ] . begin ( ) , m [ i ] . end ( ) ) ; max = * max_element ( m [ i ] . begin ( ) , m [ i ] . end ( ) ) ; cout << max - min ; break ; } else if ( i == m . size ( ) - 1 ) cout << -1 ; } } int main ( ) { int arr [ ] = { 121 , 312 , 234 , 211 , 112 , 102 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findDiff ( arr , N ) ; return 0 ; }