Difference between maximum and minimum of a set of anagrams from an array
Last Updated :
23 Apr, 2023
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++
#include <bits/stdc++.h>
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;
}
|
Java
import java.util.*;
class GFG{
static int hashFunction( int N)
{
int [] prime = { 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;
}
static void findDiff( int [] arr, int n)
{
HashMap<Integer, Vector<Integer>> m = new HashMap<>();
int h, min, max;
for ( int i = 0 ; i < n; i++)
{
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 (i.getValue().size() > 1 )
{
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);
}
}
System.out.print(max - min);
break ;
}
else if (m.get(i.getKey()) == m.values().toArray()[m.size() - 1 ])
System.out.print(- 1 );
}
}
public static void main(String[] args)
{
int [] arr = { 121 , 312 , 234 ,
211 , 112 , 102 };
int N = arr.length;
findDiff(arr, N);
}
}
|
Python3
import math
from collections import defaultdict
def hashFunction(N) :
prime = [ 2 , 3 , 5 , 7 , 11 ,
13 , 17 , 19 , 23 , 29 ]
value = 1
while (N ! = 0 ) :
r = N % 10
value = value * prime[r]
N = N / / 10
return value
def findDiff(arr, n):
m = defaultdict( lambda : [])
for i in range (n):
h = hashFunction(arr[i])
m[h].append(arr[i])
i = 0
while (i ! = len (m)) :
if ( len (m[i]) > 1 ) :
minn = min (m[i])
maxx = max (m[i])
print (maxx - minn)
break
elif (i = = ( len (m) - 1 )) :
print ( - 1 )
i + = 1
arr = [ 121 , 312 , 234 ,
211 , 112 , 102 ]
N = len (arr)
findDiff(arr, N)
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG {
static int hashFunction( int N)
{
int [] prime = { 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;
}
static void findDiff( int [] arr, int n)
{
Dictionary< int , List< int >> m = new Dictionary< int , List< int >>();
int h, min, max;
for ( int i = 0; i < n; i++) {
h = hashFunction(arr[i]);
if (!m.ContainsKey(h))
{
m[h] = new List< int >();
}
m[h].Add(arr[i]);
}
foreach (KeyValuePair< int , List< int >> i in m)
{
if (i.Value.Count > 1) {
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];
}
}
Console.Write(max - min);
break ;
}
else if (m[i.Key].Equals( m.Last().Value ))
Console.Write(-1);
}
}
static void Main()
{
int [] arr = { 121, 312, 234,
211, 112, 102 };
int N = arr.Length;
findDiff(arr, N);
}
}
|
Javascript
<script>
function hashFunction(N)
{
let prime = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ];
let value = 1, r;
while (N != 0)
{
r = N % 10;
value = value * prime[r];
N = parseInt(N / 10, 10);
}
return value;
}
function findDiff(arr, n)
{
let m = new Map();
let h, min, max;
for (let i = 0; i < n; i++) {
h = hashFunction(arr[i]);
if (!m.has(h))
{
m.set(h, []);
}
(m.get(h)).push(arr[i]);
}
m.forEach((values,keys)=>{
if (values.length > 1) {
min = Number.MAX_VALUE;
max = Number.MIN_VALUE;
for (let j = 0; j < values.length; j++)
{
if ((m.get(keys))[j] < min)
{
min = m.get(keys)[j];
}
if (m.get(keys)[j] > max)
{
max = m.get(keys)[j];
}
}
document.write(max - min);
}
})
}
let arr = [ 121, 312, 234, 211, 112, 102 ];
let N = arr.length;
findDiff(arr, N);
</script>
|
Time Complexity: O(N*logN), The time complexity of the code is O(nlog n) because the hash function takes O(log N) time to compute for each element of the array, and we do this for all n elements of the array. Then we iterate over the map and find the minimum and maximum element of each vector, which takes O(nlog n) time. Therefore, the overall time complexity of the code is O(n*log n).
Auxiliary Space: O(N), The space complexity of the code is O(n) because we create a dictionary that can store up to n key-value pairs. Each key-value pair can have a list of integers, which can also have up to n elements. Therefore, the maximum space required by the code is O(n).
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...