In this post, we will solve Equalize the Array HackerRank Solution. This problem (Equalize the Array) is a part of HackerRank Algorithms series.
Task
Given an array of integers, determine the minimum number of elements to delete to leave only elements of equal value.
Example
arr = [1, 2, 2, 3]
Delete the 2 elements 1 and 3 leaving arr = [2, 2]. If both twos plus either the 1 or the 3 are deleted, it takes 3 deletions to leave either [3] or [1]. The minimum number of deletions is 2.
Function Description
Complete the equalizeArray function in the editor below.
equalizeArray has the following parameter(s):
- int arr[n]: an array of integers
Returns
- int: the minimum number of deletions required
Input Format
The first line contains an integer n, the number of elements in arr.
The next line contains n space-separated integers arr[i].
Constraints
- 1 <= n <= 100
- 1 <= arr[i] <= 100
Sample Input
STDIN Function
----- --------
5 arr[] size n = 5
3 3 2 1 3 arr = [3, 3, 2, 1, 3]
Sample Output
2
Explanation
Delete arr[2] = 2 and arr[3] = 1 to leave arr‘ = [3, 3, 3]. This is minimal. The only other options are to delete 4 elements to get an array of either [1] or [2].
Solution – Equalize the Array – HackerRank Solution
C++
#include <bits/stdc++.h> using namespace std; #define DEBUG(x) cerr << #x << " = " << x << endl #define INPUT freopen("Data.inp", "r", stdin) #define OUTPUT freopen("Data.out", "w", stdout) typedef long long LL; typedef pair<int, int> II; typedef vector<int> VI; const int N = (int) 1e2 + 10; int n, a[N], c[N]; int main() { #ifdef LOCAL INPUT; OUTPUT; #endif scanf("%d", &n); for (int i = 1; i <= n; ++i) scanf("%d", &a[i]); for (int i = 1; i <= n; ++i) c[a[i]]++; printf("%d", n - *max_element(c + 1, c + 101)); return 0; }
Python
#!/bin/python3 import math import os import random import re import sys # Complete the equalizeArray function below. def equalizeArray(arr): return (len(arr) - arr.count(max(set(arr), key = arr.count))) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) arr = list(map(int, input().rstrip().split())) result = equalizeArray(arr) fptr.write(str(result) + '\n') fptr.close()
Java
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int[] occurances = new int[101]; int n = in.nextInt(); int maxOccurances = 0; //int[] a = new int[n]; for (int i = 0; i < n; i++) { int ai = in.nextInt(); occurances[ai]++; if (occurances[ai] > maxOccurances) { maxOccurances = occurances[ai]; } } System.out.println(n - maxOccurances); } }
Note: This problem (Equalize the Array) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.