Difference between maximum and minimum of a set of anagrams from an array
Given an array arr[] consisting of N integers, the task is to find the integers whose digits are anagrams of each other and print the difference between their maximum and minimum. If none of the numbers forms anagrams, then print -1.
Note: At most one set of array elements can be anagrams of each other. The array contains at least two numbers and all the numbers in the given array are of the same length.
Examples:
Input: arr[] = {121, 312, 234, 211, 112, 102}
Output: 99
Explanation: In the given array, the set {121, 211, 112} are anagrams of each other.
The largest value from the set is 211.
The smallest value from the set is 112.
Therefore, difference = 211 – 112 = 99.Input: arr[] = {345, 441, 604, 189, 113}
Output: -1
Approach: The idea is to use Hashing to determine the anagrams by generating a unique hash value for each anagram number. Follow the steps below to solve the problem:
- Use prime numbers for the hashing purpose and assign the first 10 prime numbers to the digits 0-9 by initializing an array prime[10] with the first 10 prime numbers.
prime[10] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}
prime[0] = 2 i.e. prime number corresponding to the digit 0 is “2”
prime[1] = 3 i.e. prime number corresponding to the digit 1 is “3”
prime[2] = 5 i.e. prime number corresponding to the digit 2 is “5” and so on…
- Then, find the hash value of each array element arr[i] by multiplying the prime number corresponding to each digit of arr[i]. This way, the hash value will be different for the numbers which are not anagrams.
- Find the hash value h for each array element arr[i] using the hashfunction(N).
- Store the array elements in map with key as their hash value h.
- Traverse the map to find a vector with size greater than 1 and find its maximum and minimum elements. If no such vector is present then print -1.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;// Utility function to find the hash value// for each element of the given arrayint hashFunction(int N){ // Initialize an array with // first 10 prime numbers int prime[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; int value = 1, r; // Iterate over digits of N while (N != 0) { r = N % 10; // Update Hash Value value = value * prime[r]; // Update N N = N / 10; } return value;}// Function to find the set of anagrams in the array// and print the difference between the maximum and// minimum of these numbersvoid findDiff(int arr[], int n){ // Map to store the hash value // and the array elements having that hash value map<int, vector<int> > m; int h, min, max; for (int i = 0; i < n; i++) { // Find the hash value for each arr[i] // by calling hash function h = hashFunction(arr[i]); m[h].push_back(arr[i]); } // Iterate over the map for (auto i = 0; i != m.size(); i++) { // If size of vector at m[i] greater than 1 // then it must contain the anagrams if (m[i].size() > 1) { // Find the minimum and maximum // element of this anagrams vector min = *min_element( m[i].begin(), m[i].end()); max = *max_element( m[i].begin(), m[i].end()); // Display the difference cout << max - min; break; } // If the end of Map is reached, // then no anagrams are present else if (i == m.size() - 1) cout << -1; }}// Driver Codeint main(){ // Given array int arr[] = { 121, 312, 234, 211, 112, 102 }; // Size of the array int N = sizeof(arr) / sizeof(arr[0]); findDiff(arr, N); return 0;} |
Java
// Java program for the above approachimport java.util.*;class GFG{// Utility function to find the hash value// for each element of the given arraystatic int hashFunction(int N){ // Initialize an array with // first 10 prime numbers int[] prime = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; int value = 1, r; // Iterate over digits of N while (N != 0) { r = N % 10; // Update Hash Value value = value * prime[r]; // Update N N = N / 10; } return value;}// Function to find the set of anagrams in the array// and print the difference between the maximum and// minimum of these numbersstatic void findDiff(int[] arr, int n){ // Map to store the hash value // and the array elements having that hash value HashMap<Integer, Vector<Integer>> m = new HashMap<>(); int h, min, max; for(int i = 0; i < n; i++) { // Find the hash value for each arr[i] // by calling hash function h = hashFunction(arr[i]); if (!m.containsKey(h)) { m.put(h, new Vector<Integer>()); } m.get(h).add(arr[i]); } for(Map.Entry<Integer, Vector<Integer>> i : m.entrySet()) { // If size of vector at m[i] greater than 1 // then it must contain the anagrams if (i.getValue().size() > 1) { // Find the minimum and maximum // element of this anagrams vector min = Integer.MAX_VALUE; max = -(Integer.MAX_VALUE); for (int j = 0; j < i.getValue().size(); j++) { if (m.get(i.getKey()).get(j) < min) { min = m.get(i.getKey()).get(j); } if (m.get(i.getKey()).get(j) > max) { max = m.get(i.getKey()).get(j); } } // Display the difference System.out.print(max - min); break; } // If the end of Map is reached, // then no anagrams are present else if (m.get(i.getKey()) == m.values().toArray()[m.size() - 1]) System.out.print(-1); }}// Driver codepublic static void main(String[] args){ // Given array int[] arr = { 121, 312, 234, 211, 112, 102 }; // Size of the array int N = arr.length; findDiff(arr, N);}}// This code is contributed by divyeshrabadiya07 |
Python3
# Python3 program for the above approachimport mathfrom collections import defaultdict# Utility function to find the hash value# for each element of the given arraydef hashFunction(N) : # Initialize an array with # first 10 prime numbers prime = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ] value = 1 # Iterate over digits of N while (N != 0) : r = N % 10 # Update Hash Value value = value * prime[r] # Update N N = N // 10 return value# Function to find the set of anagrams in the array# and print the difference between the maximum and# minimum of these numbersdef findDiff(arr, n): # Map to store the hash value # and the array elements having that hash value m = defaultdict(lambda : []) for i in range(n): # Find the hash value for each arr[i] # by calling hash function h = hashFunction(arr[i]) m[h].append(arr[i]) # Iterate over the map i = 0 while(i != len(m)) : # If size of vector at m[i] greater than 1 # then it must contain the anagrams if (len(m[i]) > 1) : # Find the minimum and maximum # element of this anagrams vector minn = min(m[i]) maxx = max(m[i]) # Display the difference print(maxx - minn) break # If the end of Map is reached, # then no anagrams are present elif (i == (len(m) - 1)) : print(-1) i += 1 # Driver Code# Given arrayarr = [ 121, 312, 234, 211, 112, 102 ]# Size of the arrayN = len(arr)findDiff(arr, N)# This code is contributed by sanjoy_62. |
C#
// C# program for the above approachusing System;using System.Collections.Generic;using System.Linq;class GFG { // Utility function to find the hash value // for each element of the given array static int hashFunction(int N) { // Initialize an array with // first 10 prime numbers int[] prime = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; int value = 1, r; // Iterate over digits of N while (N != 0) { r = N % 10; // Update Hash Value value = value * prime[r]; // Update N N = N / 10; } return value; } // Function to find the set of anagrams in the array // and print the difference between the maximum and // minimum of these numbers static void findDiff(int[] arr, int n) { // Map to store the hash value // and the array elements having that hash value Dictionary<int, List<int>> m = new Dictionary<int, List<int>>(); int h, min, max; for (int i = 0; i < n; i++) { // Find the hash value for each arr[i] // by calling hash function h = hashFunction(arr[i]); if(!m.ContainsKey(h)) { m[h] = new List<int>(); } m[h].Add(arr[i]); } // Iterate over the map foreach(KeyValuePair<int, List<int>> i in m) { // If size of vector at m[i] greater than 1 // then it must contain the anagrams if (i.Value.Count > 1) { // Find the minimum and maximum // element of this anagrams vector min = Int32.MaxValue; max = Int32.MinValue; for(int j = 0; j < i.Value.Count; j++) { if(m[i.Key][j] < min) { min = m[i.Key][j]; } if(m[i.Key][j] > max) { max = m[i.Key][j]; } } // Display the difference Console.Write(max - min); break; } // If the end of Map is reached, // then no anagrams are present else if (m[i.Key].Equals( m.Last().Value )) Console.Write(-1); } } // Driver code static void Main() { // Given array int[] arr = { 121, 312, 234, 211, 112, 102 }; // Size of the array int N = arr.Length; findDiff(arr, N); }}// This code is contributed by divyesh072019. |
99
Time Complexity: O(N*logN)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.


