703670. Difference between highest and lowest occurrence

Basic

Difference between highest and lowest occurrence

Summary

Given an array of integers, find the difference between the highest and lowest occurrence of each integer in the array. The problem is about finding the range of occurrences for each element in the array.

Detailed Explanation

The problem can be solved by using a hash map to store the frequency of each element in the array. Then, we iterate through the hash map to find the maximum and minimum frequencies for each element, which gives us the difference between the highest and lowest occurrence.

Here's a step-by-step breakdown:

  1. Create an empty hash map to store the frequency of each element.
  2. Iterate through the array and increment the count for each element in the hash map.
  3. Initialize two variables max_frequency and min_frequency to keep track of the maximum and minimum frequencies, respectively.
  4. Iterate through the hash map again and update max_frequency and min_frequency for each element.
  5. Calculate the difference between max_frequency and min_frequency to find the range of occurrences for each element.

Time complexity: O(n), where n is the size of the array, as we are iterating through the array once to build the hash map and again to update the maximum and minimum frequencies.

Space complexity: O(m), where m is the number of unique elements in the array, as we need to store the frequency of each element in the hash map.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.HashMap;
import java.util.Map;

public class HighestAndLowestOccurrence {
    public static int[] findDifference(int[] arr) {
        Map<Integer, Integer> freqMap = new HashMap<>();
        for (int num : arr) {
            freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
        }
        int[] result = new int[arr.length];
        int maxFrequency = 0;
        int minFrequency = Integer.MAX_VALUE;
        for (Map.Entry<Integer, Integer> entry : freqMap.entrySet()) {
            if (entry.getValue() > maxFrequency) {
                maxFrequency = entry.getValue();
            }
            if (entry.getValue() < minFrequency) {
                minFrequency = entry.getValue();
            }
        }
        for (int i = 0; i < arr.length; i++) {
            result[i] = Math.abs(maxFrequency - minFrequency);
        }
        return result;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.