Maximum element in an array which is equal to its frequency
Last Updated :
29 Oct, 2023
Given an array of integers arr[] of size N, the task is to find the maximum element in the array whose frequency equals to it's value
Examples:
Input: arr[] = {3, 2, 2, 3, 4, 3}
Output: 3
Frequency of element 2 is 2
Frequency of element 3 is 3
Frequency of element 4 is 1
2 and 3 are elements which have same frequency as it's value and 3 is the maximum.
Input: arr[] = {1, 2, 3, 4, 5, 6}
Output: 1
Approach: Store the frequency of every element of the array using the map, and finally find out the maximum of those element whose frequency is equal to their value.
Algorithm:
Step 1: Start
Step 2: Create a static function with an int return type name "find_maxm" which takes an array and an integer value as input parameter.
a. Create a map "mpp" of integer type to store the frequency of each element in the array arr.
b. start a for loop and traverse through i = 0 to n-1
c. For each element in the array, increment the frequency count in the map "mpp".
Step 3: Create an int variable "ans" and initialize it with 0.
Step 4: Traverse the map "mpp" using a for-each loop.
a. Set x.first to value and x.second to freq for each key-value pair x in the map.
b. Verify that the value and frequency are equivalent.
c. If the answer is yes, see if it exceeds the current value of ans. Update ans with the value if the answer is yes.
d. Give the ans value back.
Step 5: End
Below is the implementation of the above approach:
CPP
// C++ program to find the maximum element
// whose frequency equals to it’s value
#include <bits/stdc++.h>
using namespace std;
// Function to find the maximum element
// whose frequency equals to it’s value
int find_maxm(int arr[], int n)
{
// Hash map for counting frequency
map<int, int> mpp;
for (int i = 0; i < n; i++) {
// Counting freq of each element
mpp[arr[i]] += 1;
}
int ans = 0;
for (auto x : mpp)
{
int value = x.first;
int freq = x.second;
// Check if value equals to frequency
// and it is the maximum element or not
if (value == freq) {
ans = max(ans, value);
}
}
return ans;
}
// Driver code
int main()
{
int arr[] = { 3, 2, 2, 3, 4, 3 };
// Size of array
int n = sizeof(arr) / sizeof(arr[0]);
// Function call
cout << find_maxm(arr, n);
return 0;
}
Java
// Java program to find the maximum element
// whose frequency equals to it’s value
import java.util.*;
class GFG{
// Function to find the maximum element
// whose frequency equals to it’s value
static int find_maxm(int arr[], int n)
{
// Hash map for counting frequency
HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>();
for (int i = 0; i < n; i++) {
// Counting freq of each element
if(mp.containsKey(arr[i])){
mp.put(arr[i], mp.get(arr[i])+1);
}else{
mp.put(arr[i], 1);
}
}
int ans = 0;
for (Map.Entry<Integer,Integer> x : mp.entrySet())
{
int value = x.getKey();
int freq = x.getValue();
// Check if value equals to frequency
// and it is the maximum element or not
if (value == freq) {
ans = Math.max(ans, value);
}
}
return ans;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 3, 2, 2, 3, 4, 3 };
// Size of array
int n = arr.length;
// Function call
System.out.print(find_maxm(arr, n));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 program to find the maximum element
# whose frequency equals to it’s value
# Function to find the maximum element
# whose frequency equals to it’s value
def find_maxm(arr, n) :
# Hash map for counting frequency
mpp = {}
for i in range(0,n):
# Counting freq of each element
if(arr[i] in mpp):
mpp.update( {arr[i] : mpp[arr[i]] + 1} )
else:
mpp[arr[i]] = 1
ans = 0
for value,freq in mpp.items():
# Check if value equals to frequency
# and it is the maximum element or not
if (value == freq):
ans = max(ans, value)
return ans
# Driver code
arr = [ 3, 2, 2, 3, 4, 3 ]
# Size of array
n = len(arr)
# Function call
print(find_maxm(arr, n))
# This code is contributed by Sanjit_Prasad
C#
// C# program to find the maximum element
// whose frequency equals to it’s value
using System;
using System.Collections.Generic;
class GFG{
// Function to find the maximum element
// whose frequency equals to it’s value
static int find_maxm(int []arr, int n)
{
// Hash map for counting frequency
Dictionary<int,int> mp = new Dictionary<int,int>();
for (int i = 0; i < n; i++) {
// Counting freq of each element
if(mp.ContainsKey(arr[i])){
mp[arr[i]] = mp[arr[i]]+1;
}else{
mp.Add(arr[i], 1);
}
}
int ans = 0;
foreach (KeyValuePair<int,int> x in mp)
{
int value = x.Key;
int freq = x.Value;
// Check if value equals to frequency
// and it is the maximum element or not
if (value == freq) {
ans = Math.Max(ans, value);
}
}
return ans;
}
// Driver code
public static void Main(String[] args)
{
int []arr = { 3, 2, 2, 3, 4, 3 };
// Size of array
int n = arr.Length;
// Function call
Console.Write(find_maxm(arr, n));
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// Javascript program to find the maximum element
// whose frequency equals to it’s value
// Function to find the maximum element
// whose frequency equals to it’s value
function find_maxm(arr, n)
{
// Hash map for counting frequency
var mpp = new Map();
for (var i = 0; i < n; i++)
{
// Counting freq of each element
if(mpp.has(arr[i]))
mpp.set(arr[i], mpp.get(arr[i])+1)
else
mpp.set(arr[i], 1)
}
var ans = 0;
mpp.forEach((value, key) => {
var value = value;
var freq = key;
// Check if value equals to frequency
// and it is the maximum element or not
if (value == freq) {
ans = Math.max(ans, value);
}
});
return ans;
}
// Driver code
var arr = [3, 2, 2, 3, 4, 3 ];
// Size of array
var n = arr.length;
// Function call
document.write( find_maxm(arr, n));
// This code is contributed by famously.
</script>
Time Complexity : O(N)
Space Complexity : O(N) for Hash Map
where N is length of array
Approach : Using Binary Search
The idea of using Binary Search is that we can use the indices values of elements after sorting the array.
If the difference of indices is equal to its value then we can say that the no of appearances of the element is equal to its value.
Below is the implementation of the above idea.
C++
#include <iostream>
#include <algorithm>
using namespace std;
int binarySearch(int arr[], int target, int left, int right) {
int index = -1;
while (left <= right) {
int middle = left + (right - left) / 2;
// if found, keep searching forward to the last occurrence,
// otherwise, search to the left
if (arr[middle] == target) {
index = middle;
left = middle + 1;
} else {
right = middle - 1;
}
}
return index;
}
int find_max(int arr[], int n) {
sort(arr, arr + n);
int max_num = -1;
int i = 0;
while (i < n) {
int current = arr[i];
// search the last occurrence from the current index
int j = binarySearch(arr, current, i, n - 1);
// if the number of occurrences of the current element equals the
// current element itself, update the lucky integer
if ((j - i) + 1 == current) {
max_num = current;
}
// move index to the next different element
i = j + 1;
}
return max_num;
}
// Driver code
int main() {
int arr[] = { 3, 2, 2, 3, 4, 3 };
// Size of array
int n = sizeof(arr) / sizeof(arr[0]);
// Function call
cout << find_max(arr, n);
return 0;
}
Java
// Java program to find the maximum element
// whose frequency equals to it’s value
import java.util.*;
class GFG {
// Function to find the maximum element
// whose frequency equals to it’s value
public static int find_max(int[] arr,int n) {
Arrays.sort(arr);
int max_num = -1;
int i = 0;
while(i < arr.length){
int current = arr[i];
// search the last occurence from the current index
int j = binarySearch(arr, current, i, arr.length - 1);
// if the number of occurences of current element equal the
//current element itself, update the lucky integer
if((j - i) + 1 == current){
max_num = current;
}
// move index to the next different element
i = j + 1;
}
return max_num;
}
public static int binarySearch(int[] arr, int target, int left, int right){
int index = -1;
while(left <= right){
int middle = left + (right - left) / 2;
// if found, keep searching fwd to the last occurence,
//otherwise, search to the left
if(arr[middle] == target){
index = middle;
left = middle + 1;
} else {
right = middle - 1;
}
}
return index;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 3, 2, 2, 3, 4, 3 };
// Size of array
int n = arr.length;
// Function call
System.out.print(find_max(arr, n));
}
}
// This code is contributed by aeroabrar_31
Python3
def binarySearch(arr, target, left, right):
index = -1
while left <= right:
middle = left + (right - left) // 2
# if found, keep searching forward to the last occurrence,
# otherwise, search to the left
if arr[middle] == target:
index = middle
left = middle + 1
else:
right = middle - 1
return index
def find_max(arr, n):
arr.sort()
max_num = -1
i = 0
while i < n:
current = arr[i]
# search the last occurrence from the current index
j = binarySearch(arr, current, i, n - 1)
# if the number of occurrences of the current element equals the
# current element itself, update the lucky integer
if (j - i) + 1 == current:
max_num = current
# move index to the next different element
i = j + 1
return max_num
# Driver code
if __name__ == "__main__":
arr = [3, 2, 2, 3, 4, 3]
# Size of array
n = len(arr)
# Function call
print(find_max(arr, n))
C#
using System;
class Program
{
static void Main(string[] args)
{
int[] arr = { 3, 2, 2, 3, 4, 3 };
// Function call
Console.WriteLine(FindMax(arr));
}
static int FindMax(int[] arr)
{
// Sort the array in ascending order
Array.Sort(arr);
int maxNum = -1;
int i = 0;
while (i < arr.Length)
{
int current = arr[i];
// Search for the last occurrence of the current element
int j = BinarySearch(arr, current, i, arr.Length - 1);
// If the number of occurrences of the current element equals
// the current element itself, update the lucky integer
if ((j - i) + 1 == current)
{
maxNum = current;
}
// Move the index to the next different element
i = j + 1;
}
return maxNum;
}
static int BinarySearch(int[] arr, int target, int left, int right)
{
int index = -1;
while (left <= right)
{
int middle = left + (right - left) / 2;
// If found, keep searching forward to the last occurrence,
// otherwise, search to the left
if (arr[middle] == target)
{
index = middle;
left = middle + 1;
}
else
{
right = middle - 1;
}
}
return index;
}
}
JavaScript
function findMax(arr) {
arr.sort((a, b) => a - b);
let maxNum = -1;
let i = 0;
while (i < arr.length) {
const current = arr[i];
// Search the last occurrence from the current index
const j = binarySearch(arr, current, i, arr.length - 1);
// If the number of occurrences of the current element equals the
// current element itself, update the lucky integer
if ((j - i) + 1 === current) {
maxNum = current;
}
// Move index to the next different element
i = j + 1;
}
return maxNum;
}
function binarySearch(arr, target, left, right) {
let index = -1;
while (left <= right) {
const middle = left + Math.floor((right - left) / 2);
// If found, keep searching forward to the last occurrence,
// otherwise, search to the left
if (arr[middle] === target) {
index = middle;
left = middle + 1;
} else {
right = middle - 1;
}
}
return index;
}
// Driver code
const arr = [3, 2, 2, 3, 4, 3];
// Function call
console.log(findMax(arr));
Time Complexity : O(N logN)
Space Complexity : O(1)
So far, we have reduced the space complexity from linear to constant.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read