703827. Remove minimum number of elements

Easy

Here is the detailed Markdown blog post for the problem:

Remove minimum number of elements

Summary

Given an array of integers, remove the minimum number of elements to make all elements in the array equal. The goal is to find the smallest possible number of elements to remove such that all remaining elements are equal.

This problem involves arrays and hash tables, which are used to keep track of the frequency of each element in the array.

Detailed Explanation

The solution to this problem can be broken down into several steps:

  1. First, calculate the median of the array. This is because we want to make all elements equal, so we need to find a common value that is as close to the middle of the range as possible.
  2. Initialize an empty hash table (or dictionary) to keep track of the frequency of each element in the array.
  3. Iterate through the array and for each element, increment its count in the hash table.
  4. Calculate the total number of elements that need to be removed by subtracting the minimum frequency from the maximum frequency.
  5. Return the calculated value as the result.

Here is a step-by-step breakdown of the solution:

 1. Calculate median of array
 2. Initialize empty hash table
 3. Iterate through array, incrementing counts in hash table
 4. Calculate total elements to remove: max - min
 5. Return calculated value as result

The time complexity of this algorithm is O(n), where n is the size of the input array, because we need to iterate through the entire array once. The space complexity is also O(n) because in the worst case, every element in the array could be unique, requiring a hash table of size n.

Optimized Solutions

Here are optimized solutions for this problem in several languages:

Java

View on GeeksforGeeks
public int minElementsToRemove(int[] arr) {
    Arrays.sort(arr);
    int median = arr[arr.length / 2];
    Map<Integer, Integer> freqMap = new HashMap<>();
    for (int num : arr) {
        freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
    }
    int minFreq = Collections.min(freqMap.values());
    return arr.length - minFreq;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.