Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Highest / Lowest Frequency Elements

Moderate
0/80
Average time to solve is 25m
profile
Contributed by
214 upvotes
Asked in company
GeeksforGeeks

Problem statement

Given an array 'v' of 'n' numbers.


Your task is to find and return the highest and lowest frequency elements.


If there are multiple elements that have the highest frequency or lowest frequency, pick the smallest element.


Example:
Input: ‘n' = 6, 'v' = [1, 2, 3, 1, 1, 4]

Output: 1 2

Explanation: The element having the highest frequency is '1', and the frequency is 3. The elements with the lowest frequencies are '2', '3', and '4'. Since we need to pick the smallest element, we pick '2'. Hence we return [1, 2].
Detailed explanation ( Input/output format, Notes, Images )
Input Format :
The first line contains one integer 'n', denoting the size of the array.

The next line contains 'n' integers, denoting the elements of the array 'v'.
Output Format :
Return an array containing the integers described above.
Note :
You do not need to print anything; It has already been taken care of. Just implement the given function.
Sample Input 1 :
6
1 2 3 1 1 4
Sample Output 1 :
1 2
Sample Explanation 1:
Input: ‘n' = 6, 'v' = [1, 2, 3, 1, 1, 4]

Output: 1 2

Explanation: The element having the highest frequency is '1', and the frequency is 3. The elements with the lowest frequencies are '2', '3', and '4'. Since we need to pick the smallest element, we pick '2'. Hence we return [1, 2].
Sample Input 2 :
6
10 10 10 3 3 3
Sample Output 2 :
3 3
Sample Explanation 2:
Input: ‘n' = 6, 'v' = [10, 10, 10, 3, 3, 3]

Output: 3 3

Explanation: Since the frequency of '3' and '10' is 3. Therefore, the element with the maximum and minimum frequency is '3'.
Expected Time Complexity :
The expected time complexity is O(n), where n is the size of the array.
Expected Space Complexity :
The expected time complexity is O(n), where n is the size of the array.
Constraints :
2 <=  n <= 10^4
1 <= v[i] <= 10^9
There are at least two distinct elements in the array.
Time Limit: 1 sec 
Hint

Can we use a hash table to store frequencies of elements?

Approaches (1)
Hash Table

We will use a ‘hash-table’ to store frequencies of elements present in the array. We would initialize a hash-table and iterate over the whole array. While iterating, we would increase the frequency of that element in the hash-table.

 

After that, we would iterate over the hash-table, and find the answers.

 

The steps are as follows:-

 

// Function to find highest/lowest frequency elements

function getFrequencies(int[] v):

  1. Int ‘n’ is the size of the array ‘v’.
  2. Initialize a hashmap ‘freq’, which will store the frequency of each element in the array.
  3. Iterate from ‘1’ to ‘n’ using variable ‘i’:
    • Increment the frequency of the element ‘v[i]’ in the hashmap ‘freq’ by ‘1’.
  4. Initialize four variables, ‘maxFreq’, ‘minFreq’, ‘maxElement’, and ‘minElement’, initially assigned to 0, n, 0, and 1e9 + 1, respectively.
  5. Iterate through the hashmap ‘freq’:
    • Suppose for the current pair, the element's value is given by the variable ‘element’, and its count is given by ‘count’.
    • If ‘count > maxFreq’:
      • Assign ‘maxElement’ to ‘element’ and ‘maxFreq’ to ‘count’.
    • Else if ‘count == maxFreq’:
      • Assign ‘maxElement’ to ‘min(maxElement, element)’.
    • If ‘count < minFreq’:
      • Assign ‘minElement’ to ‘element’ and ‘minFreq’ to ‘count’.
    • Else if ‘count == minFreq’:
      • Assign ‘minElement’ to ‘min(minElement, element)’.
  6. Initialize an array ‘ans’ which stores two elements: ' maxElement’ and ‘minElement’.
  7. Return ‘ans’.
Time Complexity

O( n ), Where 'n' is the size of the array ‘v’.

 

We are traversing over the whole array a constant number of times.

 

Hence, the time complexity is O( n ).

Space Complexity

O( n ), Where 'n' is the size of the array ‘v’.

 

In the worst-case scenario, every element of the array is unique, so therefore, in the hash-map, a entry corresponding to each element will be present.

 

Hence, the time complexity is O( n ).

Code Solution
(100% EXP penalty)
Highest / Lowest Frequency Elements
All tags
Sort by
Search icon

Interview problems

Best CPP solution

vector<int> getFrequencies(vector<int>& v) {

    // Write Your Code Here

    unordered_map<int, int> frequencyMap;

 

    // Count frequencies of each element

    for (int num : v) {

        frequencyMap[num]++;

    }

 

    int highestFrequency = 0;

    int lowestFrequency = INT_MAX;

    int highestFreqElement = INT_MAX;

    int lowestFreqElement = INT_MAX;

 

    // Find the highest and lowest frequency elements

    for (const auto& entry : frequencyMap) {

        int element = entry.first;

        int frequency = entry.second;

 

        // Check for highest frequency

        if (frequency > highestFrequency) {

            highestFrequency = frequency;

            highestFreqElement = element;

        } else if (frequency == highestFrequency) {

            highestFreqElement = min(highestFreqElement, element);

        }

 

        // Check for lowest frequency

        if (frequency < lowestFrequency) {

            lowestFrequency = frequency;

            lowestFreqElement = element;

        } else if (frequency == lowestFrequency) {

            lowestFreqElement = min(lowestFreqElement, element);

        }

    }

 

    return {highestFreqElement, lowestFreqElement};

}

41 views
0 replies
0 upvotes

Interview problems

99.83% Better Solution

from typing import List
from collections import Counter

def getFrequencies(v: List[int]) -> List[int]: 
    # Write your code here
    d = Counter(v)
    most_to_least = d.most_common()
    most_common , most_common_count = most_to_least[0][0], most_to_least[0][1]

    least_to_most = most_to_least[::-1]
    least_common,least_common_count = least_to_most[0][0],least_to_most[0][1]
    
    i,n=1,len(least_to_most)


    while(n>i):
        if( most_common > most_to_least[i][0] and most_common_count == most_to_least[i][1] ):
            most_common = most_to_least[i][0]
        if(least_common > least_to_most[i][0] and least_common_count == least_to_most[i][1]):
            least_common = least_to_most[i][0]
        i+=1

    return [most_common,least_common]
   
9 views
0 replies
0 upvotes

Interview problems

cpp solution using map

#include<bits/stdc++.h>
vector<int> getFrequencies(vector<int>& v) {
    // Write Your Code Here

    map<int,int> mpp;

    for(int i=0;i<v.size();i++){
        mpp[v[i]]++;
    }

    int minFreq=INT_MAX;
    int maxFreq=INT_MIN;
    int minValue=0;
    int maxValue=0;
    
    for(auto it: mpp){

        if(it.second>maxFreq){
            maxFreq=it.second;
            maxValue=it.first;
        }

        if(it.second<minFreq){
            minFreq=it.second;
            minValue=it.first;
        }

    }

    return {maxValue,minValue};
}
58 views
0 replies
0 upvotes

Interview problems

check my code

from typing import List

 

def getFrequencies(n :int,v: List[int]) -> List[int]: 

    frequency={}

    for num in v:

        if num in frequency:

            frequency[num]+=1

        frequency[num]=1

    highest_freq= float("-inf")

    lowest_freq= float("inf")

    highest_freq_element=float("inf")

    lowest_freq_element=float("inf")

    

    for key,values in frequency.items():

        if values>highest_freq or (values==highest_freq and key>highest_freq_element) :

            highest_freq=values

            highest_freq_element=key

            

        if values<lowest_freq or (values==lowest_freq and key<lowest_freq_element):

            lowest_freq=values

            lowest_freq_element=key

    return [highest_freq_element,lowest_freq_element]

 

    

26 views
0 replies
0 upvotes

Interview problems

In CPP (Using Unordered Map)

vector<int> getFrequencies(vector<int>& v) {

    // Calculate frequencies of elements in v

    unordered_map<int, int> ans;

 

    for(int i = 0; i < v.size(); i++) {

        ans[v[i]]++;

    }

 

    // Initialize minimum and maximum frequencies and values

    int minFreq = INT_MAX, maxFreq = 0;

    int minVal = v[0], maxVal = v[0];

 

    // Find minimum and maximum frequencies and corresponding values

    for(auto it : ans) {

        // Update minimum frequency and value

        if(minFreq >= it.second) {

            if(minFreq == it.second) {

                minVal = min(minVal, it.first);

            } else {

                minFreq = it.second;

                minVal = it.first;

            }

        }

 

        // Update maximum frequency and value

        if(maxFreq <= it.second) {

            if(maxFreq == it.second) {

                maxVal = min(maxVal, it.first);

            } else {

                maxFreq = it.second;

                maxVal = it.first;

            }

        }

    }

 

    // Return vector containing maxVal and minVal

    return {maxVal, minVal};

}

 

152 views
0 replies
1 upvote
profile

Interview problems

World's optimized solution using TreeMap

import java.util.*;

import java.util.Arrays;

public class Solution {

    public static int[] getFrequencies(int []v) {

        // Write Your Code Here

        int res[] = new int[2];

        // Arrays.sort(v);

        TreeMap<Integer,Integer> map = new TreeMap<>();

        for(int i=0;i<v.length;i++) {

            map.put(v[i], map.getOrDefault(v[i], 0)+1);

        }

 

        int lar = Integer.MIN_VALUE;

        int low = Integer.MAX_VALUE;

 

         // for largest because 1st element showing the largest element in the array

         for(Integer key : map.keySet()) {

            int val = map.get(key);

            if(val > lar) {

                lar = val;

                res[0] = key;

            }

        }

        

 

        //for lowest because 2nd element showing the lowest element in the array

        for(Integer key : map.keySet()) {

            int val = map.get(key);

            if(val < low) {

                low = val;

                res[1] = key;

            }

        }

 

       

 

        return res;

    }

}

135 views
0 replies
0 upvotes

Interview problems

Easy-peasy C++ solution

vector<int> getFrequencies(vector<int>& v) {

    // Write Your Code Here

    unordered_map<int,int> mp;

 

    for(int i=0;i<v.size();i++)

    {

        if(mp.find(v[i])!=mp.end())

        {

            mp[v[i]]++;

        }

        else mp[v[i]]=1;

    }

 

    int maxfreq = 0;

    int minfreq =INT_MAX;

    int maxfval = v[0];

    int minfval = v[0];

    for(auto it = mp.begin();it!=mp.end();it++)

    {

        

        if(it->second<=minfreq)

        {

            if(it->second == minfreq)

            {

                minfval = min(minfval,it->first);

            }

            else{

                minfreq = it->second;

                minfval = it->first;

            }

        }

        if(it->second>=maxfreq)

        {

            if(it->second == maxfreq)

            {

                maxfval = min(maxfval,it->first);

            }

            else{

                maxfreq = it->second;

                maxfval = it->first;

            }

        }

        

    }

    return {maxfval,minfval};

}

219 views
0 replies
0 upvotes

Interview problems

Easy Python Solution

from typing import List

def getFrequencies(v: List[int]) -> List[int]: 
    # Write your code here
    freq_dict = dict()
    for i in v:
        if i in freq_dict:
            freq_dict[i] += 1
        else:
            freq_dict[i] = 1
    
    max_val = max(freq_dict.values())
    min_val = min(freq_dict.values())
    
    max_list = []
    for i,j in freq_dict.items():
        if j == max_val:
            max_list.append(i)
    
    min_list = []
    for i,j in freq_dict.items():
        if j == min_val:
            min_list.append(i)
    
    return min(max_list),min(min_list)
    pass
65 views
0 replies
0 upvotes

Interview problems

easiest c++ sol using map

vector<int> getFrequencies(vector<int>& v) {

    // Write Your Code Here

    map<int, int>mpp;

    for(int i=0; i<v.size(); i++)

    {

          mpp[v[i]]++;

    }

    int maxf = 0;

     int lowest=0;

    int highest = 0;

    int minf=INT_MAX;

  map<int, int>::iterator iter;

    for( iter=mpp.begin(); iter!=mpp.end(); ++iter)

    {

          if(iter->second<minf)

          {

              minf = iter->second;

              lowest = iter->first;

          }

    }

 

     for( iter=mpp.begin(); iter!=mpp.end(); ++iter)

    {

          if(iter->second>maxf)

          {

             maxf = iter->second;

             highest = iter->first;

          }

    }

    return {highest, lowest};

}

 

150 views
0 replies
1 upvote

Interview problems

Using HashMap in Java

import java.util.*;

public class Solution {

    public static int[] getFrequencies(int []v) {

        // Write Your Code Here

        int n = v.length;

        HashMap<Integer,Integer> map = new HashMap<>();

        for(int i : v){

            if(map.containsKey(i)){

                map.put(i, map.get(i)+1);

            }else{

                map.put(i,1);

            }

        }

        int maxKey = Integer.MIN_VALUE;

        int minKey = Integer.MAX_VALUE;

        int maxCount = Integer.MIN_VALUE;

        int minCount = Integer.MAX_VALUE;

        

        for (Map.Entry<Integer, Integer> entry : map.entrySet()){

            int freq = entry.getValue();

            int key = entry.getKey();

            if(freq > maxCount){

                maxCount = freq;

                maxKey = entry.getKey();

            }

            if(freq < minCount){

                minCount = freq;

                minKey = entry.getKey();

            }

            if(freq == minCount){

                minKey = Math.min(key, minKey);

            }

            if(freq == maxCount){

                maxKey = Math.min(key, maxKey);

            }

        }

        int arr [] = new int[2];

        arr[0] = maxKey;

        arr[1] = minKey;

        return arr;

 

    }

}

319 views
0 replies
1 upvote
Full screen
Console