Top K Frequent Elements in an Array
Last Updated :
20 Aug, 2024
Given an array of n numbers and a positive integer K. The problem is to find K numbers with the most occurrences. If two numbers have the same frequency then the number with a larger value should be given preference. The numbers should be displayed in decreasing order of their frequencies. It is assumed that the array consists of at least K numbers.
Examples:
Input: arr[] = {3, 1, 4, 4, 5, 2, 6, 1}, K = 2
Output: 4 1
Explanation:
Frequency of 4 = 2, Frequency of 1 = 2
These two have the maximum frequency and 4 is larger than 1.
Input: arr[] = {7, 10, 11, 5, 2, 5, 5, 7, 11, 8, 9}, K = 4
Output: 5 11 7 10
Explanation:
Frequency of 5 = 3, Frequency of 11 = 2, Frequency of 7 = 2, Frequency of 10 = 1
These four have the maximum frequency and 5 is largest among rest.
Using Hash Map
To solve the problem using this approach follow the below idea:
create a Map to store the element-frequency pair. Map is used to perform insertion and updation in constant time. Then sort the element-frequency pair in decreasing order of frequency. This gives the information about each element and the number of times they are present in the array. To get K elements of the array, print the first K elements of the sorted array.
Follow the given steps to solve the problem:
- Create a map mp, to store key-value pair, i.e. element-frequency pair.
- Traverse the array from start to end.
- For every element in the array update mp[array[i]]++
- Store the element-frequency pair in a vector and sort the vector in decreasing order of frequency.
- Print the first k elements of the sorted array.
Below is the Implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Comparison function to sort the 'freq_arr[]'
bool compare(pair<int, int> p1, pair<int, int> p2)
{
// If frequencies of two elements are same
// then the larger number should come first
if (p1.second == p2.second)
return p1.first > p2.first;
// Sort on the basis of decreasing order
// of frequencies
return p1.second > p2.second;
}
// Function to print the k numbers with most occurrences
void topKFrequent(vector<int> arr, int N, int K)
{
// unordered_map 'mp' implemented as frequency hash
// table
unordered_map<int, int> mp;
for (int i = 0; i < N; i++)
mp[arr[i]]++;
// store the elements of 'mp' in the vector 'freq_arr'
vector<pair<int, int> > freq_arr(mp.begin(), mp.end());
// Sort the vector 'freq_arr' on the basis of the
// 'compare' function
sort(freq_arr.begin(), freq_arr.end(), compare);
// display the top k numbers
cout << K << " numbers with most occurrences are:\n";
for (int i = 0; i < K; i++)
cout << freq_arr[i].first << " ";
}
// Driver's code
int main()
{
vector<int> arr = { 3, 1, 4, 4, 5, 2, 6, 1 };
int N = arr.size();
int K = 2;
topKFrequent(arr, N, K);
return 0;
}
Java
// Java implementation to find
// K elements with max occurrence.
import java.util.*;
public class KFrequentNumbers {
static void topKFrequent(int[] arr, int N,
int K)
{
Map<Integer, Integer> mp
= new HashMap<Integer, Integer>();
// Put count of all the
// distinct elements in Map
// with element as the key &
// count as the value.
for (int i = 0; i < N; i++) {
// Get the count for the
// element if already present in the
// Map or get the default value which is 0.
mp.put(arr[i], mp.getOrDefault(arr[i], 0) + 1);
}
// Create a list from elements of HashMap
List<Map.Entry<Integer, Integer> > list
= new ArrayList<Map.Entry<Integer, Integer> >(
mp.entrySet());
// Sort the list
Collections.sort(
list,
new Comparator<Map.Entry<Integer, Integer> >() {
public int compare(
Map.Entry<Integer, Integer> o1,
Map.Entry<Integer, Integer> o2)
{
if (o1.getValue() == o2.getValue())
return o2.getKey() - o1.getKey();
else
return o2.getValue()
- o1.getValue();
}
});
for (int i = 0; i < K; i++)
System.out.print(list.get(i).getKey() + " ");
}
// Driver's Code
public static void main(String[] args)
{
int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 };
int N = arr.length;
int K = 2;
// Function call
System.out.println(
K + " numbers with most occurrences are:");
topKFrequent(arr, N, K);
}
}
Python
# Python3 implementation to find k numbers
# with most occurrences in the given array
# Function to print the k numbers with
# most occurrences
def topKFrequent(arr, N, K):
mp = {}
for i in range(N):
if arr[i] in mp:
mp[arr[i]] += 1
else:
mp[arr[i]] = 1
a = [0] * (len(mp))
j = 0
for i in mp:
a[j] = [i, mp[i]]
j += 1
a = sorted(a, key=lambda x: x[0],
reverse=True)
a = sorted(a, key=lambda x: x[1],
reverse=True)
# Display the top k numbers
print(K, "numbers with most occurrences are:")
for i in range(K):
print(a[i][0], end=" ")
# Driver code
if __name__ == "__main__":
arr = [3, 1, 4, 4, 5, 2, 6, 1]
N = 8
K = 2
# Function call
topKFrequent(arr, N, K)
C#
// C# implementation to find
// k elements with max occurrence.
using System;
using System.Collections.Generic;
public class Comparer : IComparer<KeyValuePair<int, int> > {
public int Compare(KeyValuePair<int, int> p2,
KeyValuePair<int, int> p1)
{
// If frequencies of two elements are same
// then the larger number should come first
if (p1.Value == p2.Value)
return p1.Key.CompareTo(p2.Key);
// Sort on the basis of decreasing order
// of frequencies
return p1.Value.CompareTo(p2.Value);
}
}
public class KFrequentNumbers {
static void print_N_mostFrequentNumber(int[] arr, int N,
int K)
{
IDictionary<int, int> mp
= new Dictionary<int, int>();
// Put count of all the
// distinct elements in Map
// with element as the key &
// count as the value.
for (int i = 0; i < N; i++) {
// Get the count for the
// element if already present in the
// Map or get the default value which is 0
if (mp.ContainsKey(arr[i]))
mp[arr[i]] += 1;
else
mp[arr[i]] = 1;
}
// Create a list from elements of HashMap
List<KeyValuePair<int, int> > list
= new List<KeyValuePair<int, int> >();
foreach(KeyValuePair<int, int> entry in mp)
{
list.Add(entry);
}
// Sort the list
Comparer compare = new Comparer();
list.Sort(compare);
for (int i = 0; i < K; i++)
Console.Write(list[i].Key + " ");
}
// Driver's code
public static void Main(string[] args)
{
int[] arr = { 3, 1, 4, 4, 5, 2, 6, 1 };
int N = arr.Length;
int K = 2;
Console.Write(
K + " elements with most occurrences are:\n");
// Function call
print_N_mostFrequentNumber(arr, N, K);
}
}
// this code is contributed by phasing17
JavaScript
// JavaScript implementation to find
// K elements with max occurrence.
function topKFrequent(arr, N, K) {
let mp = new Map();
// Put count of all the
// distinct elements in Map
// with element as the key &
// count as the value.
for (let i = 0; i < N; i++) {
// Get the count for the
// element if already present in the
// Map or get the default value which is 0.
if (mp.has(arr[i])) {
mp.set(arr[i], mp.get(arr[i]) + 1)
} else {
mp.set(arr[i], 1)
}
}
// Create a list from elements of HashMap
let list = [...mp];
// Sort the list
list.sort((o1, o2) => {
if (o1[1] == o2[1])
return o2[0] - o1[0];
else
return o2[1] - o1[1];
})
console.log(K + " numbers with most occurrences are: ");
for (let i = 0; i < K; i++)
console.log(list[i][0] + " ");
}
// Driver's Code
let arr = [3, 1, 4, 4, 5, 2, 6, 1];
let N = arr.length;
let K = 2;
topKFrequent(arr, N, K);
Output2 numbers with most occurrences are:
4 1
Time Complexity: O(N + D log D), where D is the count of distinct elements in the array
Auxiliary Space: O(D), where D is the count of distinct elements in the array
To solve the problem using this approach follow the below idea:
Approach: Create a Map to store element-frequency pair. Map is used to perform insertion and updation in constant time. Then use a priority queue to store the element-frequency pair (Max-Heap). The element which has maximum frequency, comes at the root of the Priority Queue. Remove the top or root of Priority Queue K times and print the element.
Follow the given steps to solve the problem:
- Create a map mp, to store key-value pair, i.e. element-frequency pair.
- Traverse the array from start to end.
- For every element in the array update mp[array[i]]++
- Store the element-frequency pair in a Priority Queue
- Run a loop k times, and in each iteration remove the root of the priority queue and print the element.
Below is the Implementation of the above approach:
C++
// C++ implementation to find k numbers with most
// occurrences in the given array
#include <bits/stdc++.h>
using namespace std;
// Comparison function defined for the priority queue
struct compare {
bool operator()(pair<int, int> p1, pair<int, int> p2)
{
// If frequencies of two elements are same
// then the larger number should come first
if (p1.second == p2.second)
return p1.first < p2.first;
// Insert elements in the priority queue on the
// basis of decreasing order of frequencies
return p1.second < p2.second;
}
};
// Function to print the k numbers with most occurrences
void topKFrequent(int arr[], int N, int K)
{
// unordered_map 'mp' implemented as frequency hash
// table
unordered_map<int, int> mp;
for (int i = 0; i < N; i++)
mp[arr[i]]++;
// priority queue 'pq' implemented as max heap on the
// basis of the comparison operator 'compare' element
// with the highest frequency is the root of 'pq' in
// case of conflicts, larger element is the root
priority_queue<pair<int, int>, vector<pair<int, int> >,
compare>
pq(mp.begin(), mp.end());
// Display the top k numbers
cout << K << " numbers with most occurrences are:\n";
for (int i = 1; i <= K; i++) {
cout << pq.top().first << " ";
pq.pop();
}
}
// Driver's code
int main()
{
int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 };
int N = sizeof(arr) / sizeof(arr[0]);
int K = 2;
topKFrequent(arr, N, K);
return 0;
}
Java
// Java implementation to find k
// elements with max occurrence.
import java.util.*;
public class KFrequentNumbers {
static void topKFrequent(int[] arr, int N,
int K)
{
Map<Integer, Integer> mp
= new HashMap<Integer, Integer>();
// Put count of all the
// distinct elements in Map
// with element as the key &
// count as the value.
for (int i = 0; i < N; i++) {
// Get the count for the
// element if already
// present in the Map or
// get the default value
// which is 0.
mp.put(arr[i], mp.getOrDefault(arr[i], 0) + 1);
}
// Create a Priority Queue
// to sort based on the
// count or on the key if the
// count is same
PriorityQueue<Map.Entry<Integer, Integer> > queue
= new PriorityQueue<>(
(a, b)
-> a.getValue().equals(b.getValue())
? Integer.compare(b.getKey(),
a.getKey())
: Integer.compare(b.getValue(),
a.getValue()));
// Insert the data from the map
// to the Priority Queue.
for (Map.Entry<Integer, Integer> entry :
mp.entrySet())
queue.offer(entry);
// Print the top k elements
for (int i = 0; i < K; i++) {
System.out.print(queue.poll().getKey() + " ");
}
}
// Driver's Code
public static void main(String[] args)
{
int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 };
int N = arr.length;
int K = 2;
System.out.println(
K + " numbers with most occurrences are:");
topKFrequent(arr, N, K);
}
}
Python
# Python3 implementation to find k
# numbers with most occurrences in
# the given array
import heapq
# Function to print the k numbers with
# most occurrences
def topKFrequent(arr, N, K):
mp = dict()
# Put count of all the distinct elements
# in dictionary with element as the
# key & count as the value.
for i in range(0, N):
if arr[i] not in mp:
mp[arr[i]] = 0
else:
mp[arr[i]] += 1
# Using heapq data structure
heap = [(value, key) for key,
value in mp.items()]
# Get the top k elements
largest = heapq.nlargest(K, heap)
# Insert the data from the map to
# the priority queue
print(K, " numbers with most "
"occurrences are:", sep="")
# Print the top k elements
for i in range(K):
print(largest[i][1], end=" ")
# Driver's code
if __name__ == "__main__":
arr = [3, 1, 4, 4, 5, 2, 6, 1]
N = len(arr)
K = 2
topKFrequent(arr, N, K)
C#
// C# implementation to find k
// elements with max occurrence.
using System;
using System.Collections.Generic;
using System.Linq;
public class KFrequentNumbers {
static void print_N_mostFrequentNumber(int[] arr, int N,
int K)
{
Dictionary<int, int> mp
= new Dictionary<int, int>();
// Put count of all the
// distinct elements in Map
// with element as the key &
// count as the value.
for (int i = 0; i < N; i++) {
// Get the count for the
// element if already
// present in the Map or
// get the default value
// which is 0.
if (!mp.ContainsKey(arr[i]))
mp[arr[i]] = 0;
mp[arr[i]]++;
}
// Create a Priority Queue
// to sort based on the
// count or on the key if the
// count is same
List<int> queue = mp.Keys.ToList();
queue.Sort(delegate(int y, int x) {
if (mp[x] == mp[y])
return x.CompareTo(y);
else
return (mp[x]).CompareTo(mp[y]);
});
// Print the top k elements
Console.WriteLine(
K + " numbers with the most occurrences are:");
for (int i = 0; i < K; i++) {
Console.WriteLine(queue[i] + " ");
}
}
// Driver's Code
public static void Main(string[] args)
{
int[] arr = { 3, 1, 4, 4, 5, 2, 6, 1 };
int N = arr.Length;
int K = 2;
// Function call
print_N_mostFrequentNumber(arr, N, K);
}
}
// This code is contributed by phasing17
JavaScript
// Javascript implementation to find k
// elements with max occurrence.
function topKFrequent(arr, N, K)
{
let mp = new Map();
// Put count of all the
// distinct elements in Map
// with element as the key &
// count as the value.
for (let i = 0; i < N; i++) {
// Get the count for the
// element if already
// present in the Map or
// get the default value
// which is 0.
if(!mp.has(arr[i]))
mp.set(arr[i],0);
mp.set(arr[i],
mp.get(arr[i]) + 1);
}
// Create a Priority Queue
// to sort based on the
// count or on the key if the
// count is same
let queue=[...mp];
queue.sort(function(a,b){
if(a[1]==b[1])
{
return b[0]-a[0];
}
else
{
return b[1]-a[1];
}
});
console.log(K + " numbers with most "+"occurrences are: ")
for(let i=0; i<K; i++)
{
console.log(queue[i][0]+" ");
}
}
// Driver's Code
let arr = [3, 1, 4, 4, 5, 2, 6, 1];
let N = arr.length;
let K = 2;
topKFrequent(arr, N, K);
Output2 numbers with most occurrences are:
4 1
Time Complexity: O(N + K log D + D), where D is the count of distinct elements in the array.
- To insert N elements in a hash, we need O(N) time
- To remove the top of the priority queue O(log d) time is required, so if k elements are removed then O(k log d) time is required, and
- To construct a priority queue with D elements, O(D) time is required.
Auxiliary Space: O(D), where D is the count of distinct elements in the array.
Using Quick Select:
In quick select we partition the array of unique numbers in such a way that the elements to the left of pivotpivotpivot are more frequent than pivot, and elements to the right of pivotare less frequent than pivot. Thus we can say the pivotis in its sorted position. We randomly chose such pivot until we finally find its sorted position to be K. Then we know that all the elements to the left of pivot are more frequent than pivotand each time we reduce our paritioning space w.r.t the pivot.
Partition Algorithm
Let’s imagine the pivot at store_point. If the iiith element is more frequent than pivot, then the ith element will be on the left of pivot, but the store_point is instead holding an element which is either equally or less frequent than pivot, so it should go to the right of pivot. Hence, we swap the two elements and move store_point forward so that the more frequent element is on the left. If iiith element is less frequent than pivot we assume pivot is at its right place and don’t move store_point .
At the end we swap store_point with pivot and return the sorted index.
C++
// C++ program to find k numbers with most
// occurrences in the given array
#include <bits/stdc++.h>
using namespace std;
vector<int> topKFrequent(vector<int>& nums, int k)
{
// map for counting the number of
// occurences
unordered_map<int, int> counts;
// stroing the frequency of each element
for (int num : nums)
++counts[num];
// creating a vector for storing the
// frequency
vector<pair<int, int> > freqs;
for (auto vt : counts)
freqs.push_back({ vt.second, vt.first });
// using the library function
// nth_element to extract the values
nth_element(freqs.begin(), freqs.end() - k,
freqs.end());
vector<int> result;
transform(freqs.end() - k, freqs.end(), back_inserter(result),
[](pair<int, int> vt) { return vt.second; });
return result;
}
// Driver's code
int main()
{
vector<int> arr{ 3, 1, 4, 4, 5, 2, 6, 1 };
int K = 2;
// Function call
vector<int> ans = topKFrequent(arr, K);
cout << K
<< " numbers with most occurences are : " << endl;
for (int i = ans.size() - 1; i >= 0; i--) {
cout << ans[i] << " ";
}
return 0;
}
Java
// JAVA program to find k numbers with most
// occurrences in the given array
import java.util.*;
class Main {
static List<Integer>
print_N_mostFrequentNumber(List<Integer> nums, int k,
List<Integer> out)
{
// Map for counting the number of occurrences
Map<Integer, Integer> counts = new HashMap<>();
// Storing the frequency of each element
for (int num : nums)
counts.put(num,
counts.getOrDefault(num, 0) + 1);
// Creating a list for storing the frequency
List<Map.Entry<Integer, Integer> > freqs
= new ArrayList<>(counts.entrySet());
// Using the user-defined function Collections.sort
// to sort by frequency
Collections.sort(
freqs, (a, b) -> b.getValue() - a.getValue());
// Adding the k most frequent numbers to the output
// list
for (int i = 0; i < k; i++)
out.add(freqs.get(i).getKey());
// Returning the result in the out list
return out;
}
// Driver's code
public static void main(String[] args)
{
List<Integer> arr = new ArrayList<>(
Arrays.asList(3, 1, 4, 4, 5, 2, 6, 1));
int k = 2;
// Function call
List<Integer> ans = new ArrayList<>(k);
print_N_mostFrequentNumber(arr, k, ans);
System.out.println(
k + " numbers with most occurrences are:");
for (int i = ans.size() - 1; i >= 0; i--) {
System.out.print(ans.get(i) + " ");
}
}
}
// This code is contributed by shivamgupta0987654321
Python
# Python3 program to find k numbers with most
# occurrences in the given array
from collections import Counter
def print_N_mostFrequentNumber(nums, k, out):
# Count the occurrences of each number
counts = Counter(nums)
# Get the k numbers with the highest occurrences
most_frequent = counts.most_common(k)
# Extract the numbers from the most frequent pairs
numbers = [num for num, _ in most_frequent]
# Store the numbers in the output list
for i, num in enumerate(numbers):
out[i] = num
return out
# Driver's code
arr = [3, 1, 4, 4, 5, 2, 6, 1]
K = 2
# Function call
ans = [0] * K
print_N_mostFrequentNumber(arr, K, ans)
print(K, "numbers with most occurrences are:")
print(ans[::-1])
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
// Function to find k numbers with most occurrences in the given array
static List<int> PrintNMostFrequentNumber(List<int> nums, int k)
{
// Dictionary for counting the number of occurrences
Dictionary<int, int> counts = new Dictionary<int, int>();
// Storing the frequency of each element
foreach (int num in nums)
{
if (counts.ContainsKey(num))
counts[num]++;
else
counts[num] = 1;
}
// Creating a list to store the frequency
List<Tuple<int, int>> freqs = new List<Tuple<int, int>>();
foreach (var kvp in counts)
{
freqs.Add(new Tuple<int, int>(kvp.Value, kvp.Key));
}
// Using the user-defined function (CustomNthElement) to extract the values
CustomNthElement(freqs, k);
// Using user-defined function Transform to make the desired changes
List<int> outList = freqs.GetRange(freqs.Count - k, k).Select(t => t.Item2).ToList();
// Return the result
return outList;
}
// Custom implementation of nth_element
static void CustomNthElement(List<Tuple<int, int>> freqs, int k)
{
int left = 0;
int right = freqs.Count - 1;
while (left <= right)
{
int pivot = Partition(freqs, left, right);
if (pivot == freqs.Count - k)
return;
else if (pivot < freqs.Count - k)
left = pivot + 1;
else
right = pivot - 1;
}
}
// Partition function for the custom nth_element
static int Partition(List<Tuple<int, int>> freqs, int left, int right)
{
int pivot = freqs[right].Item1;
int i = left;
for (int j = left; j < right; j++)
{
if (freqs[j].Item1 <= pivot)
{
Swap(freqs, i, j);
i++;
}
}
Swap(freqs, i, right);
return i;
}
// Helper function to swap elements in the list
static void Swap(List<Tuple<int, int>> freqs, int i, int j)
{
Tuple<int, int> temp = freqs[i];
freqs[i] = freqs[j];
freqs[j] = temp;
}
static void Main(string[] args)
{
List<int> arr = new List<int> { 3, 1, 4, 4, 5, 2, 6, 1 };
int K = 2;
// Function call
List<int> ans = PrintNMostFrequentNumber(arr, K);
Console.WriteLine(K + " numbers with most occurrences are : ");
for (int i = ans.Count - 1; i >= 0; i--)
{
Console.Write(ans[i] + " ");
}
}
}
JavaScript
function printNMostFrequentNumber(nums, k, out) {
// Count the occurrences of each number
let counts = new Map();
for (let num of nums) {
counts.set(num, (counts.get(num) || 0) + 1);
}
// Get the k numbers with the highest occurrences
let mostFrequent = Array.from(counts.entries()).sort((a, b) => b[1] - a[1]).slice(0, k);
// Extract the numbers from the most frequent pairs
let numbers = mostFrequent.map(([num, _]) => num);
// Store the numbers in the output array
for (let i = 0; i < numbers.length; i++) {
out[i] = numbers[i];
}
return out;
}
// Driver's code
let arr = [3, 1, 4, 4, 5, 2, 6, 1];
let K = 2;
// Function call
let ans = new Array(K).fill(0);
printNMostFrequentNumber(arr, K, ans);
console.log(`${K} numbers with most occurrences are:`);
console.log(ans.reverse());
Output2 numbers with most occurences are :
4 1
Time complexity: O(N + D^2). The QuickSelect algorithm takes O(D Log D) time on average and works faster than other O(D Log D) algorithms in practice
Auxiliary Space: O(N)
Using Counting Sort
- Create a HashMap elementCount and store the count of the elements in the given array.
- Create a 2D vector frequency of size N+1 to store the elements according to their frequencies.
- Now initialize a variable count = 0.
- While count < K:
- Traverse the frequency array from N till 0 and print the elements present in the vector and increment the count for each element.
Below is the implementation of above approach:
C++
// C++ program to find k numbers with most
// occurrences in the given array
#include <bits/stdc++.h>
using namespace std;
// Function to print the k numbers with most occurrences
void topKFrequent(vector<int>& arr, int K)
{
// HashMap to store count of the elements
unordered_map<int, int> elementCount;
for (int i = 0; i < arr.size(); i++) {
elementCount[arr[i]]++;
}
// Vector to store the elements according
// to their frequency
vector<vector<int> > frequency(arr.size() + 1);
// Inserting elements in the frequency array
for (auto element : elementCount) {
frequency[element.second].push_back(element.first);
}
int count = 0;
cout << K << " numbers with most occurrences are:\n";
for (int i = frequency.size() - 1; i >= 0; i--) {
// if frequency is same,then take number with a
// larger value
// so,if more than 1 number present with same
// frequency,then sort frequency[i] in descending
// order.
if (frequency[i].size() > 1) {
sort(frequency[i].begin(), frequency[i].end(),
greater<int>());
}
for (auto element : frequency[i]) {
count++;
cout << element << " ";
// if K elements have been printed
if (count >= K)
return;
}
}
return;
}
// Driver's code
int main()
{
vector<int> arr = { 3, 1, 4, 4, 5, 2, 6, 1 };
int K = 2;
topKFrequent(arr, K);
return 0;
}
Java
import java.util.*;
class Main {
// Function to print the k numbers with most occurrences
static void topKFrequent(int arr[], int N,
int K)
{
// HashMap to store count of the elements
HashMap<Integer, Integer> elementCount
= new HashMap<>();
for (int i = 0; i < N; i++) {
elementCount.put(
arr[i],
elementCount.getOrDefault(arr[i], 0) + 1);
}
// Array to store the elements according
// to their frequency
List<List<Integer> > frequency = new ArrayList<>();
for (int i = 0; i < N + 1; i++) {
frequency.add(new ArrayList<>());
}
// Inserting elements in the frequency array
for (int element : elementCount.keySet()) {
frequency.get(elementCount.get(element))
.add(element);
}
int count = 0;
System.out.println(
K + " numbers with most occurrences are: ");
for (int i = frequency.size() - 1; i >= 0; i--) {
// if frequency is same,then take number with a
// larger value
// so,if more than 1 number present with same
// frequency,then sort frequency[i] in
// descending order
if (frequency.get(i).size() > 1) {
Collections.sort(
frequency.get(i),
Collections.reverseOrder());
}
for (int element : frequency.get(i)) {
count++;
System.out.print(element + " ");
// if K elements have been printed
if (count == K)
return;
}
}
return;
}
public static void main(String[] args)
{
int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 };
int N = arr.length;
int K = 2;
// Function call
topKFrequent(arr, N, K);
}
}
Python
def topKFrequent(arr, N, K):
# HashMap to store count of the elements
count = {}
# Array to store the elements according
# to their frequency
freq = [[] for i in range(len(arr) + 1)]
for n in arr:
count[n] = 1 + count.get(n, 0)
for n, c in count.items():
freq[c].append(n)
res = []
# if K elements have been printed
for i in range(len(freq)-1, 0, -1):
for n in freq[i]:
res.append(n)
if len(res) == K:
return res[-1::-1]
# Driver's code
if __name__ == "__main__":
arr = [3, 1, 4, 4, 5, 2, 6, 1]
N = len(arr)
K = 2
# Function call
print(topKFrequent(arr, N, K))
C#
// C# program to find k numbers with most
// occurrences in the given array
using System;
using System.Collections.Generic;
class GFG {
// Function to print the k numbers with most occurrences
static void topKFrequent(int[] arr, int N,
int K)
{
// HashMap to store count of the elements
Dictionary<int, int> elementCount
= new Dictionary<int, int>();
for (int i = 0; i < N; i++) {
if (elementCount.ContainsKey(arr[i])) {
elementCount[arr[i]]++;
}
else {
elementCount.Add(arr[i], 1);
}
}
// Array to store the elements according
// to their frequency
List<int>[] frequency = new List<int>[ N + 1 ];
for (int i = 0; i <= N; i++) {
frequency[i] = new List<int>();
}
// Inserting elements in the frequency array
foreach(
KeyValuePair<int, int> element in elementCount)
{
frequency[element.Value].Add(element.Key);
}
int count = 0;
Console.WriteLine(
K + " numbers with most occurrences are:");
for (int i = N; i >= 0; i--) {
// if frequency is same,then take number with
// a
// larger value
// so,if more than 1 number present with same
// frequency,then sort frequency[i] in
// descending order
if (frequency[i].Count > 1) {
frequency[i].Sort();
frequency[i].Reverse();
}
foreach(int element in frequency[i])
{
count += 1;
Console.Write(element + " ");
// if K elements have been printed
if (count == K)
return;
}
}
return;
}
// Driver's code
public static void Main(string[] args)
{
int[] arr = { 3, 1, 4, 4, 5, 2, 6, 1 };
int N = 8;
int K = 2;
topKFrequent(arr, N, K);
}
}
// This code is contributed by shubhamm050402
JavaScript
// JavaScript program to find k numbers with most
// occurrences in the given array
// Function to print the k numbers with most occurrences
function topKFrequent(arr, N, K)
{
// HashMap to store count of the elements
let elementCount = new Map();
for (let i = 0; i < N; i++) {
if (elementCount.has(arr[i])) {
let temp = elementCount.get(arr[i]);
elementCount.set(arr[i], temp + 1);
}
else {
elementCount.set(arr[i], 1);
}
}
// Array to store the elements according
// to their frequency
let frequency = new Array(N + 1);
for (let i = 0; i <= N; i++) {
frequency[i] = new Array();
}
// Inserting elements in the frequency array
for (const [key, value] of elementCount.entries()) {
frequency[value].push(key);
}
let count = 0;
console.log(K + " numbers with most occurrences are:" +
"<br>");
for (let i = N; i >= 0; i--) {
for (let j = frequency[i].length - 1; j >= 0; j--) {
count++;
console.log(frequency[i][j] + " ");
}
// if K elements have been printed
if (count == K) {
return;
}
}
return;
}
let arr = [ 3, 1, 4, 4, 5, 2, 6, 1 ];
let N = arr.length;
let K = 2;
topKFrequent(arr, N, K);
Output2 numbers with most occurrences are:
4 1
Time Complexity: O(N + D), where N is the size of the given array. worst case is when all the elements are the same, we are sorting the entire vector.
Auxiliary Space: O(N + D)
Similar Reads
Heap Data Structure
A Heap is a complete binary tree data structure that satisfies the heap property: for every node, the value of its children is greater than or equal to its own value. Heaps are usually used to implement priority queues, where the smallest (or largest) element is always at the root of the tree. Basic
2 min read
Introduction to Heap - Data Structure and Algorithm Tutorials
A Heap is a special Tree-based Data Structure that has the following properties. It is a Complete Binary Tree.It either follows max heap or min heap property.Max-Heap: The value of the root node must be the greatest among all its descendant nodes and the same thing must be done for its left and righ
15+ min read
Binary Heap
A Binary Heap is a complete Binary Tree which is used to store data efficiently to get the max or min element based on its type. A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be re
14 min read
Advantages and Disadvantages of Heap
Advantages of Heap Data StructureTime Efficient: Heaps have an average time complexity of O(log n) for inserting and deleting elements, making them efficient for large datasets. We can convert any array to a heap in O(n) time. The most important thing is, we can get the min or max in O(1) timeSpace
2 min read
Time Complexity of building a heap
Consider the following algorithm for building a Heap of an input array A. A quick look over the above implementation suggests that the running time is [Tex]O(n * lg(n)) [/Tex] since each call to Heapify costs [Tex]O(lg(n)) [/Tex]and Build-Heap makes [Tex]O(n) [/Tex]such calls. This upper bound, thou
2 min read
Applications of Heap Data Structure
Heap Data Structure is generally taught with Heapsort. Heapsort algorithm has limited uses because Quicksort is better in practice. Nevertheless, the Heap data structure itself is enormously used. Priority Queues: Heaps are commonly used to implement priority queues, where elements with higher prior
2 min read
Comparison between Heap and Tree
What is Heap? A Heap is a special Tree-based data structure in which the tree is a complete binary tree. Types of Heap Data Structure: Generally, Heaps can be of two types: Max-Heap: In a Max-Heap the key present at the root node must be greatest among the keys present at all of its children. The sa
3 min read
When building a Heap, is the structure of Heap unique?
What is Heap? A heap is a tree based data structure where the tree is a complete binary tree that maintains the property that either the children of a node are less than itself (max heap) or the children are greater than the node (min heap). Properties of Heap: Structural Property: This property sta
4 min read
Easy problems on Heap
Check if a given Binary Tree is a Heap
Given a binary tree, check if it has heap property or not, Binary tree needs to fulfil the following two conditions for being a heap: It should be a complete tree (i.e. all levels except the last should be full).Every nodeâs value should be greater than or equal to its child node (considering max-he
15+ min read
How to check if a given array represents a Binary Heap?
Given an array, how to check if the given array represents a Binary Max-Heap.Examples: Input: arr[] = {90, 15, 10, 7, 12, 2} Output: True The given array represents below tree 90 / \ 15 10 / \ / 7 12 2 The tree follows max-heap property as every node is greater than all of its descendants. Input: ar
11 min read
Iterative HeapSort
HeapSort is a comparison-based sorting technique where we first build Max Heap and then swap the root element with the last element (size times) and maintains the heap property each time to finally make it sorted. Examples: Input : 10 20 15 17 9 21 Output : 9 10 15 17 20 21 Input: 12 11 13 5 6 7 15
11 min read
Find k largest elements in an array
Given an array arr[] and an integer k, the task is to find k largest elements in the given array. Elements in the output array should be in decreasing order. Examples: Input: [1, 23, 12, 9, 30, 2, 50], K = 3Output: [50, 30, 23] Input: [11, 5, 12, 9, 44, 17, 2], K = 2Output: [44, 17] Table of Content
15+ min read
Kâth Smallest Element in Unsorted Array
Given an array arr[] of N distinct elements and a number K, where K is smaller than the size of the array. Find the K'th smallest element in the given array. Examples: Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 3 Output: 7 Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 4 Output: 10 Table of Content [Naive
15+ min read
Height of a complete binary tree (or Heap) with N nodes
Consider a Binary Heap of size N. We need to find the height of it. Examples: Input : N = 6 Output : 2 () / \ () () / \ / () () () Input : N = 9 Output : 3 () / \ () () / \ / \ () () () () / \ () ()Recommended PracticeHeight of HeapTry It! Let the size of the heap be N and the height be h. If we tak
3 min read
Heap Sort for decreasing order using min heap
Given an array of elements, sort the array in decreasing order using min heap. Examples: Input : arr[] = {5, 3, 10, 1} Output : arr[] = {10, 5, 3, 1} Input : arr[] = {1, 50, 100, 25} Output : arr[] = {100, 50, 25, 1} Prerequisite: Heap sort using min heap. Algorithm : Build a min heap from the input
13 min read
Medium problems on Heap
Print all nodes less than a value x in a Min Heap.
Given a binary min heap and a value x, print all the binary heap nodes having value less than the given value x. Examples : Consider the below min heap as common input two both below examples. 2 / \ 3 15 / \ / \ 5 4 45 80 / \ / \ 6 150 77 120 Input : x = 15 Output : 2 3 5 6 4 Input : x = 80 Output :
9 min read
Tournament Tree (Winner Tree) and Binary Heap
Given a team of N players. How many minimum games are required to find the second-best player? We can use adversary arguments based on the tournament tree (Binary Heap). A Tournament tree is a form of min (max) heap which is a complete binary tree. Every external node represents a player and the int
6 min read
Connect n ropes with minimum cost
Given an array arr[] of rope lengths, connect all ropes into a single rope with the minimum total cost. The cost to connect two ropes is the sum of their lengths. Examples: Input: arr[] = [4, 3, 2, 6]Output: 29Explanation: We can connect the ropes in following ways.1) First connect ropes of lengths
6 min read
Maximum distinct elements after removing k elements
Given an array arr[] containing n elements. The problem is to find the maximum number of distinct elements (non-repeating) after removing k elements from the array. Note: 1 <= k <= n.Examples: Input : arr[] = {5, 7, 5, 5, 1, 2, 2}, k = 3 Output : 4 Remove 2 occurrences of element 5 and 1 occur
10 min read
K maximum sum combinations from two arrays
Given two equally sized arrays (A, B) and N (size of both arrays). A sum combination is made by adding one element from array A and another element of array B. Display the maximum K valid sum combinations from all the possible sum combinations. Examples: Input : A[] : {3, 2} B[] : {1, 4} K : 2 [Numb
15 min read
Median of Stream of Running Integers using STL
Given that integers are being read from a data stream. Find the median of all the elements read so far starting from the first integer till the last integer. This is also called the Median of Running Integers. The data stream can be any source of data, for example, a file, an array of integers, inpu
9 min read
Find Median from Running Data Stream
Given that integers are read from a data stream. Find the median of elements read so far in an efficient way. There are two cases for median on the basis of data set size. If the data set has an odd number then the middle one will be consider as median.If the data set has an even number then there i
15 min read
Largest triplet product in a stream
Given a stream of integers represented as arr[]. For each index i from 0 to n-1, print the multiplication of largest, second largest, third largest element of the subarray arr[0...i]. If i < 2 print -1. Examples: Input : arr[] = {1, 2, 3, 4, 5} Output :-1 -1 6 24 60 Explanation : for i = 2 only t
5 min read
Top K Frequent Elements in an Array
Given an array of n numbers and a positive integer K. The problem is to find K numbers with the most occurrences. If two numbers have the same frequency then the number with a larger value should be given preference. The numbers should be displayed in decreasing order of their frequencies. It is ass
15+ min read
Convert Min Heap to Max Heap
Given an array representation of min Heap, convert it to max Heap. Examples: Input: arr[] = {3, 5, 9, 6, 8, 20, 10, 12, 18, 9} 3 / \ 5 9 / \ / \ 6 8 20 10 / \ /12 18 9 Output: arr[] = {20, 18, 10, 12, 9, 9, 3, 5, 6, 8} 20 / \ 18 10 / \ / \ 12 9 9 3 / \ /5 6 8 Input: arr[] = {3, 4, 8, 11, 13}Output:
10 min read
Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
Given the level order traversal of a Complete Binary Tree, determine whether the Binary Tree is a valid Min-Heap Examples: Input : level = [10, 15, 14, 25, 30] Output : True The tree of the given level order traversal is 10 / \ 15 14 / \ 25 30 We see that each parent has a value less than its child,
6 min read
Hard problems on Heap
Design an efficient data structure for given operations
To design an efficient data structure for a specific set of operations, it's important to consider the time and space complexity of different data structures and choose the one that is best suited for the specific requirements. For example, if you need to perform operations such as inserting element
15+ min read
Merge k Sorted Arrays
Given K sorted arrays, merge them and print the sorted output. Examples: Input: K = 3, arr = { {1, 3, 5, 7}, {2, 4, 6, 8}, {0, 9, 10, 11}}Output: 0 1 2 3 4 5 6 7 8 9 10 11 Input: k = 4, arr = { {1}, {2, 4}, {3, 7, 9, 11}, {13} }Output: 1 2 3 4 7 9 11 13 Table of Content Naive - Concatenate all and S
15+ min read
Merge Sort Tree for Range Order Statistics
Given an array of n numbers, the task is to answer the following queries: kthSmallest(start, end, k) : Find the Kth smallest number in the range from array index 'start' to 'end'. Examples: Input : arr[] = {3, 2, 5, 1, 8, 9| Query 1: start = 2, end = 5, k = 2 Query 2: start = 1, end = 6, k = 4 Outpu
15 min read
Smallest Derangement of Sequence
Given the sequence [Tex]\ S = {1, 2, 3 \dots N} [/Tex]find the lexicographically smallest (earliest in dictionary order) derangement of [Tex]\ S [/Tex]A derangement of S is any permutation of S such that no two elements in S and its permutation occur at the same position. Examples: Input: 3 Output :
11 min read
Largest Derangement of a Sequence
Given any sequence, find the largest derangement of .A derangement [Tex]D [/Tex]is any permutation of, such that no two elements at the same position in [Tex]S [/Tex]and [Tex]D [/Tex]are equal. The Largest Derangement is such that. Examples: Input : seq[] = {5, 4, 3, 2, 1}Output : 4 5 2 1 3 Input :
7 min read
Maximum difference between two subsets of m elements
Given an array of n integers and a number m, find the maximum possible difference between two sets of m elements chosen from given array. Examples: Input : arr[] = 1 2 3 4 5 m = 4 Output : 4 The maximum four elements are 2, 3, 4 and 5. The minimum four elements are 1, 2, 3 and 4. The difference betw
4 min read
Merge Two Binary Max Heaps
Given two binary max heaps, the task is to merge the given heaps to form a new max heap. Examples :Â Input: a[] = {10, 5, 6, 2}, b[] = {12, 7, 9}Output: {12, 10, 9, 2, 5, 7, 6} Input: a[] = {2, 5, 1, 9, 12}, b[] = {3, 7, 4, 10}Output: {12, 10, 7, 9, 5, 3, 1, 4, 2} Table of Content [Naive Approach] U
12 min read
K-th Largest Sum Contiguous Subarray
Given an array of integers. Write a program to find the K-th largest sum of contiguous subarray within the array of numbers that has both negative and positive numbers. Examples: Input: a[] = {20, -5, -1}, K = 3Output: 14Explanation: All sum of contiguous subarrays are (20, 15, 14, -5, -6, -1) so th
15+ min read
Minimum product of k integers in an array of positive Integers
Given an array of n positive integers. We are required to write a program to print the minimum product of k integers of the given array. Examples:Â Input : 198 76 544 123 154 675 k = 2Output : 9348We get minimum product after multiplying76 and 123.Input : 11 8 5 7 5 100 k = 4Output : 1400Recommended
6 min read
Leaf starting point in a Binary Heap data structure
Binary Heap is a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). In other words, we can say that it's an almost complete binary tree. A Binary heap is typically represented as array. If we take a closer look, we can
2 min read
Sum of all elements between k1'th and k2'th smallest elements
Given an array of integers and two numbers k1 and k2. Find the sum of all elements between given two k1'th and k2'th smallest elements of the array. It may be assumed that (1 <= k1 < k2 <= n) and all elements of array are distinct. Examples : Input : arr[] = {20, 8, 22, 4, 12, 10, 14}, k1 =
15+ min read
Minimum sum of two numbers formed from digits of an array
Given an array of digits (values are from 0 to 9), find the minimum possible sum of two numbers formed from digits of the array. All digits of given array must be used to form the two numbers. Examples: Input: [6, 8, 4, 5, 2, 3] Output: 604 The minimum sum is formed by numbers 358 and 246 Input: [5,
10 min read