Open In App

Difference between maximum and minimum of a set of anagrams from an array

Last Updated : 23 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 array
int 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 numbers
void 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 Code
int 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 approach
import java.util.*;
 
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
    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 code
public 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 approach
import math
from collections import defaultdict
 
# Utility function to find the hash value
# for each element of the given array
def 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 numbers
def 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 array
arr = [ 121, 312, 234,
                211, 112, 102 ]
 
# Size of the array
N = len(arr)
findDiff(arr, N)
 
# This code is contributed by sanjoy_62.


C#




// C# program for the above approach
using 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.


Javascript




<script>
    // Javascript program for the above approach
     
    // Utility function to find the hash value
    // for each element of the given array
    function hashFunction(N)
    {
 
        // Initialize an array with
        // first 10 prime numbers
        let prime = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ];
 
        let value = 1, r;
 
        // Iterate over digits of N
        while (N != 0)
        {
            r = N % 10;
 
            // Update Hash Value
            value = value * prime[r];
 
            // Update N
            N = parseInt(N / 10, 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
    function findDiff(arr, n)
    {
 
      // Map to store the hash value
      // and the array elements having that hash value
      let m = new Map();
 
      let h, min, max;
      for (let i = 0; i < n; i++) {
 
        // Find the hash value for each arr[i]
        // by calling hash function
        h = hashFunction(arr[i]);
 
        if(!m.has(h))
        {
          m.set(h, []);
        }
 
        (m.get(h)).push(arr[i]);
      }
 
      // Iterate over the map
      m.forEach((values,keys)=>{
        // If size of vector at m[i] greater than 1
        // then it must contain the anagrams
        if (values.length > 1) {
 
          // Find the minimum and maximum
          // element of this anagrams vector
          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];
            }
          }
 
          // Display the difference
          document.write(max - min);
        }
      })
    }
     
    // Given array
    let arr = [ 121, 312, 234, 211, 112, 102 ];
  
    // Size of the array
    let N = arr.length;
  
    findDiff(arr, N);
 
// This code is contributed by suresh07.
</script>


Output: 

99

 

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
Previous
Next
Share your thoughts in the comments

Similar Reads