Minimum distance between any most frequent and least frequent element of an array

Given an integer array arr[] of size N, the task is to find the minimum distance between any most and least frequent element of the given array.

Examples:

Input: arr[] = {1, 1, 2, 3, 2, 3, 3}
Output: 1
Explanation: The least frequent elements are 1 and 2 which occurs at indexes: 0, 1, 2, 4. 
Whereas, the most frequent element is 3 which occurs at indexes: 3, 5, 6.
So the minimum distance is (3-2) = 1.

Input: arr[] = {1, 3, 4, 4, 3, 4}
Output: 2
Explanation: The least frequent element is 1 which occurs at indexes: 0. 
Whereas, the most frequent element is 4 which occurs at indexes: 2, 3, 5. 
So the minimum distance is (2-0) = 2.
 

 

Approach: The idea is to find the indices of least and most frequent elements in the array and find the difference between those indices  which is minimum. Follow the steps below to solve the problem:



  1. Store the frequency of each element in a HashMap.
  2. Store the least and most frequent elements in separate Sets.
  3. Traverse from the start of the array. If the current element is the least frequent element then update the last index of the least frequent element.
  4. Otherwise, if the current element is the most frequent element then calculate the distance between the current and the last index of the least frequent element and update the required minimum distance.
  5. Similarly, traverse the array from the end and repeat step 3 and step 4 to find the minimum distance between any most and least frequent element of an array.
  6. Print the minimum distance.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
import java.util.*;
  
class GFG {
  
    // Function to find the minimum
    // distance between any two most
    // and least frequent element
    public static void
    getMinimumDistance(int a[], int n)
    {
  
        // Initialize sets to store the least
        // and the most frequent elements
        Set<Integer> min_set = new HashSet<>();
        Set<Integer> max_set = new HashSet<>();
  
        // Initialize variables to store
        // max and min frequency
        int max = 0, min = Integer.MAX_VALUE;
  
        // Initialize HashMap to store
        // frequency of each element
        HashMap<Integer, Integer> frequency
            = new HashMap<>();
  
        // Loop through the array
        for (int i = 0; i < n; i++) {
  
            // Store the count of each element
            frequency.put(
                a[i],
                frequency
                        .getOrDefault(a[i], 0)
                    + 1);
        }
  
        // Store the least and most frequent
        // elements in the respective sets
        for (int i = 0; i < n; i++) {
  
            // Store count of current element
            int count = frequency.get(a[i]);
  
            // If count is equal
            // to max count
            if (count == max) {
  
                // Store in max set
                max_set.add(a[i]);
            }
  
            // If count is greater
            // then max count
            else if (count > max) {
  
                // Empty max set
                max_set.clear();
  
                // Update max count
                max = count;
  
                // Store in max set
                max_set.add(a[i]);
            }
  
            // If count is equal
            // to min count
            if (count == min) {
  
                // Store in min set
                min_set.add(a[i]);
            }
  
            // If count is less
            // then max count
            else if (count < min) {
  
                // Empty min set
                min_set.clear();
  
                // Update min count
                min = count;
  
                // Store in min set
                min_set.add(a[i]);
            }
        }
  
        // Initialize a variable to
        // store the minimum distance
        int min_dist = Integer.MAX_VALUE;
  
        // Initialize a variable to
        // store the last index of
        // least frequent element
        int last_min_found = -1;
  
        // Traverse array
        for (int i = 0; i < n; i++) {
  
            // If least frequent element
            if (min_set.contains(a[i]))
  
                // Update last index of
                // least frequent element
                last_min_found = i;
  
            // If most frequent element
            if (max_set.contains(a[i])
                && last_min_found != -1) {
  
                // Update minimum distance
                min_dist = Math.min(min_dist,
                                    i - last_min_found);
            }
        }
  
        last_min_found = -1;
  
        // Traverse array from the end
        for (int i = n - 1; i >= 0; i--) {
  
            // If least frequent element
            if (min_set.contains(a[i]))
  
                // Update last index of
                // least frequent element
                last_min_found = i;
  
            // If most frequent element
            if (max_set.contains(a[i])
                && last_min_found != -1) {
  
                // Update minimum distance
                min_dist = Math.min(min_dist,
                                    last_min_found - i);
            }
        }
  
        // Print the minimum distance
        System.out.println(min_dist);
    }
  
    // Driver Code
    public static void
        main(String[] args)
    {
        // Given array
        int arr[] = { 1, 1, 2, 3, 2, 3, 3 };
  
        int N = arr.length;
  
        // Function Call
        getMinimumDistance(arr, N);
    }
}
chevron_right

Output:
1

Time Complexity: O(N), where N is the length of the array.
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.





Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :