Top K Frequent Elements in an Array
Last Updated :
23 Jul, 2025
Given an array arr[] and a positive integer k, the task is to find the k most frequently occurring elements from a given array.
Note: If more than one element has same frequency then prioritise the larger element over the smaller one.
Examples:
Input: arr= [3, 1, 4, 4, 5, 2, 6, 1], k = 2
Output: [4, 1]
Explanation: Frequency of 4 is 2 and frequency of 1 is 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 is 3, frequency of 11 is 2, frequency of 7 is 2, frequency of 10 is 1. These four have the maximum frequency and 5 is largest among rest.
[Naive Approach] Using hash map and Sorting
The idea is to use a hashmap to store the element-frequency pair. Hashmap 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.
C++
// c++ program to find k most frequent element
// using hash map and sorting
#include <iostream>
#include <unordered_map>
#include <algorithm>
#include <vector>
using namespace std;
// Comparison function to sort the frequency array
static bool compare(pair<int, int> &p1, pair<int, int> &p2) {
// Prioritise element's value incase their frequency was same
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 find k numbers with most occurrences
vector<int> topKFrequent(vector<int>&arr,int k) {
int n = arr.size();
// 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'
vector<pair<int, int>> freq(mp.begin(), mp.end());
// Sort the vector 'freq' on the basis of the
// 'compare' function
sort(freq.begin(), freq.end(), compare);
vector<int>res;
// Extract and store the top k frequent elements
for (int i = 0; i < k; i++)
res.push_back(freq[i].first);
return res;
}
int main() {
vector<int> arr = {3, 1, 4, 4, 5, 2, 6, 1};
int k = 2;
vector<int> res = topKFrequent(arr, k);
for(int val : res)
cout << val << " ";
}
Java
// Java program to find k most frequent element
// using hash map and sorting
import java.util.*;
class GfG {
// Comparison function to sort the frequency array
static class Compare implements Comparator<int[]> {
public int compare(int[] p1, int[] p2) {
// Prioritise element's value in case their frequency was same
if (p1[1] == p2[1])
return Integer.compare(p2[0], p1[0]);
// Sort on the basis of decreasing order
// of frequencies
return Integer.compare(p2[1], p1[1]);
}
}
// Function to find k numbers with most occurrences
static ArrayList<Integer> topKFrequent(int[] arr, int k) {
int n = arr.length;
// HashMap 'mp' implemented as frequency hash table
Map<Integer, Integer> mp = new HashMap<>();
for (int i = 0; i < n; i++)
mp.put(arr[i], mp.getOrDefault(arr[i], 0) + 1);
// Store the elements of 'mp' in the list 'freq'
ArrayList<int[]> freq = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : mp.entrySet())
freq.add(new int[]{entry.getKey(), entry.getValue()});
// Sort the list 'freq' on the basis of the
// 'compare' function
freq.sort(new Compare());
ArrayList<Integer> res = new ArrayList<>();
for (int i = 0; i < k; i++) {
res.add(freq.get(i)[0]);
}
return res;
}
public static void main(String[] args) {
int[] arr = {3, 1, 4, 4, 5, 2, 6, 1};
int k = 2;
ArrayList<Integer> res = topKFrequent(arr, k);
for (int val : res)
System.out.print(val + " ");
}
}
Python
# Python program to find k most frequent element
# using hash map and sorting
from collections import Counter
# Function to find k numbers with most occurrences
def topKFrequent(arr, k):
n = len(arr)
# Dictionary 'mp' implemented as frequency hash table
mp = Counter(arr)
# Store the elements of 'mp' in the list 'freq'
freq = list(mp.items())
# Sort the list 'freq' on the basis of the
# 'compare' function
freq.sort(key=lambda x: (x[1], x[0]), reverse=True)
res = []
# Extract and store the top k frequent elements
for i in range(k):
res.append(freq[i][0])
return res
if __name__ == "__main__":
arr = [3, 1, 4, 4, 5, 2, 6, 1]
k = 2
res = topKFrequent(arr, k)
for val in res:
print(val, end=" ")
C#
// C# program to find k most frequent element
// using hash map and sorting
using System;
using System.Collections.Generic;
using System.Linq;
class GfG {
// Comparison function to sort the frequency array
class FrequencyComparer : IComparer<int[]> {
public int Compare(int[] p1, int[] p2) {
// Prioritise element's value
// in case their frequency is same
if (p1[1] == p2[1])
return p2[0].CompareTo(p1[0]);
// Sort on the basis of decreasing order
// of frequencies
return p2[1].CompareTo(p1[1]);
}
}
// Function to find k numbers with most occurrences
static List<int> TopKFrequent(int[] arr, int k) {
int n = arr.Length;
// Dictionary 'mp' implemented as frequency hash table
Dictionary<int, int> mp = new Dictionary<int, int>();
foreach (int num in arr) {
if (mp.ContainsKey(num))
mp[num]++;
else
mp[num] = 1;
}
// Store the elements of 'mp' in the list 'freq'
List<int[]> freq = new List<int[]>();
foreach (var entry in mp)
freq.Add(new int[] { entry.Key, entry.Value });
// Sort the list 'freq' on the basis of the
// 'FrequencyComparer' function
freq.Sort(new FrequencyComparer());
List<int> res = new List<int>();
// Extract and store the top k frequent elements
for (int i = 0; i < k; i++)
res.Add(freq[i][0]);
return res;
}
public static void Main() {
int[] arr = { 3, 1, 4, 4, 5, 2, 6, 1 };
int k = 2;
List<int> res = TopKFrequent(arr, k);
foreach (int val in res)
Console.Write(val + " ");
}
}
JavaScript
// JavaScript program to find k most frequent element
// using hash map and sorting
// Comparison function to sort the frequency array
function compare(p1, p2) {
// Prioritise element's value in case their frequency was same
if (p1[1] === p2[1])
return p2[0] - p1[0];
// Sort on the basis of decreasing order
// of frequencies
return p2[1] - p1[1];
}
// Function to find k numbers with most occurrences
function topKFrequent(arr, k) {
let n = arr.length;
// Object 'mp' implemented as frequency hash table
let mp = {};
for (let i = 0; i < n; i++)
mp[arr[i]] = (mp[arr[i]] || 0) + 1;
// Store the elements of 'mp' in the array 'freq'
let freq = Object.entries(mp).map(([key, value]) => [parseInt(key), value]);
// Sort the array 'freq' on the basis of the
// 'compare' function
freq.sort(compare);
let res = [];
// Extract and store the top k frequent elements
for (let i = 0; i < k; i++)
res.push(freq[i][0]);
return res;
}
// Driver code
let arr = [3, 1, 4, 4, 5, 2, 6, 1];
let k = 2;
let res = topKFrequent(arr, k);
console.log(res.join(" "));
Time Complexity: O(n +d*log d), where n is the size of the array and d is the count of distinct elements in the array.
Auxiliary Space: O(d)
[Expected Approach 1] Using hash map and Max Heap
The idea is to use a hashmap to store the element-frequency pair. Then use a priority queue (Max-Heap) to store the frequency-element pair. The element which has maximum frequency, comes at the top of the Priority Queue. Remove the top of Priority Queue k times and store the values in the result array.
C++
// c++ program to find k most
// frequent element using max heap
#include <algorithm>
#include <iostream>
#include <queue>
#include <unordered_map>
#include <vector>
using namespace std;
// Function to find k numbers with most occurrences
vector<int> topKFrequent(vector<int> &arr, int k) {
// unordered_map 'mp' implemented as frequency hash
// table
unordered_map<int, int> mp;
for (int val: arr)
mp[val]++;
priority_queue<pair<int, int>,
vector<pair<int, int>>, greater<pair<int, int>>> pq;
for (pair<int, int> entry : mp) {
pq.push({entry.second, entry.first});
if (pq.size() > k)
pq.pop();
}
// store the result
vector<int> res(k);
for (int i = k-1; i >= 0; i--) {
res[i] = pq.top().second;
pq.pop();
}
return res;
}
int main() {
vector<int> arr = {3, 1, 4, 4, 5, 2, 6, 1};
int k = 2;
vector<int> res = topKFrequent(arr, k);
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
}
Java
// Java program to find k most
// frequent element using max heap
import java.util.*;
class GfG {
// Comparison function to sort the frequency array
static class Compare implements Comparator<int[]> {
public int compare(int[] p1, int[] p2) {
// Prioritise element's value in case their frequency was same
if (p1[0] == p2[0])
return Integer.compare(p1[1], p2[1]);
// Sort on the basis of increasing order
// of frequencies (for min heap behavior)
return Integer.compare(p1[0], p2[0]);
}
}
// Function to find k numbers with most occurrences
static ArrayList<Integer> topKFrequent(int[] arr, int k) {
// HashMap 'mp' implemented as frequency hash
// table
Map<Integer, Integer> mp = new HashMap<>();
for (int val : arr)
mp.put(val, mp.getOrDefault(val, 0) + 1);
// Priority queue (Min-Heap) with custom comparator
PriorityQueue<int[]> pq = new PriorityQueue<>(new Compare());
for (Map.Entry<Integer, Integer> entry : mp.entrySet()) {
pq.offer(new int[]{entry.getValue(), entry.getKey()});
if (pq.size() > k)
pq.poll();
}
// store the result
ArrayList<Integer> res = new ArrayList<>();
while (!pq.isEmpty()) {
res.add(pq.poll()[1]);
}
Collections.reverse(res);
return res;
}
public static void main(String[] args) {
int[] arr = {3, 1, 4, 4, 5, 2, 6, 1};
int k = 2;
ArrayList<Integer> res = topKFrequent(arr, k);
for (int i = 0; i < res.size(); i++)
System.out.print(res.get(i) + " ");
}
}
Python
# Python program to find k most
# frequent element using max heap
import heapq
from collections import Counter
# Function to find k numbers with most occurrences
def topKFrequent(arr, k):
# Dictionary 'mp' implemented as frequency hash
# table
mp = Counter(arr)
pq = []
for key, value in mp.items():
heapq.heappush(pq, (value, key))
if len(pq) > k:
heapq.heappop(pq)
# store the result
res = []
while pq:
res.append(heapq.heappop(pq)[1])
res.reverse()
return res
if __name__ == "__main__":
arr = [3, 1, 4, 4, 5, 2, 6, 1]
k = 2
res = topKFrequent(arr, k)
for i in range(len(res)):
print(res[i], end=" ")
JavaScript
// JavaScript program to find k most
// frequent element using min heap
class MinHeap {
constructor() {
this.heap = [];
}
// Swap elements
swap(i, j) {
[this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];
}
// Get parent index
parent(i) {
return Math.floor((i - 1) / 2);
}
// Get left child index
leftChild(i) {
return 2 * i + 1;
}
// Get right child index
rightChild(i) {
return 2 * i + 2;
}
// Insert an element into the heap
push(val) {
this.heap.push(val);
this.heapifyUp(this.heap.length - 1);
}
// Remove and return the smallest element
pop() {
if (this.heap.length === 0) return null;
if (this.heap.length === 1) return this.heap.pop();
let top = this.heap[0];
this.heap[0] = this.heap.pop();
this.heapifyDown(0);
return top;
}
// Heapify up (used when inserting)
heapifyUp(index) {
while (index > 0 && this.compare(this.heap[index], this.heap[this.parent(index)]) < 0) {
this.swap(index, this.parent(index));
index = this.parent(index);
}
}
// Heapify down (used when deleting)
heapifyDown(index) {
let smallest = index;
let left = this.leftChild(index);
let right = this.rightChild(index);
// Use custom comparison function
if (left < this.heap.length && this.compare(this.heap[left], this.heap[smallest]) < 0)
smallest = left;
if (right < this.heap.length && this.compare(this.heap[right], this.heap[smallest]) < 0)
smallest = right;
if (smallest !== index) {
this.swap(index, smallest);
this.heapifyDown(smallest);
}
}
// Custom comparison function (implements the Java comparator logic)
compare(p1, p2) {
if (p1[0] === p2[0])
return p1[1] - p2[1]; // Prioritize larger numbers when frequencies are the same
return p1[0] - p2[0]; // Sort by increasing frequency
}
// Return the top element without removing it
top() {
return this.heap.length > 0 ? this.heap[0] : null;
}
// Return the size of the heap
size() {
return this.heap.length;
}
}
// Function to find k numbers with most occurrences
function topKFrequent(arr, k) {
// Map 'mp' implemented as frequency hash
// table
let mp = new Map();
for (let val of arr)
mp.set(val, (mp.get(val) || 0) + 1);
let pq = new MinHeap();
for (let [key, value] of mp.entries()) {
pq.push([value, key]); // Store as [frequency, number]
if (pq.size() > k)
pq.pop();
}
// store the result
let res = [];
while (pq.size() > 0) {
res.push(pq.pop()[1]);
}
res.reverse();
return res;
}
// Driver code
let arr = [3, 1, 4, 4, 5, 2, 6, 1];
let k = 2;
let res = topKFrequent(arr, k);
console.log(res.join(" "));
Time Complexity: O(n + k*log k ), where n is the size of array.
Auxiliary Space: O(d), where d is the count of distinct elements in the array.
[Expected Approach 2] Using Counting sort
The idea is to utilise more space to improve the time complexity, we store the elements based on their frequencies. We can use the frequency of each element as index of 2D array, where each index represents a list of elements of specific frequency. By doing this, we reduce the need for complex sorting operations. Instead, we can efficiently traverse the buckets from highest frequency to lowest and collect the top k most frequent elements.
Steps by step implementation:
- First, we count the frequency of each element in the array using an hashmap.
- We use an array of lists (buckets) where the index represents the frequency of elements. For example, elements that appear i times will be stored in the ith bucket.
- Then we sort the elements in each bucket in descending order.
- Finally, we start from the highest frequency and collect all the top k frequent elements and store then in result array.
C++
// c++ program to find k most
// frequent element using counting sort
#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> topKFrequent(vector<int>& arr, int k) {
// Count frequency of each element
unordered_map<int, int> freq;
for (int num : arr) {
freq[num]++;
}
//Find the maximum frequency
int maxFreq = 0;
for (pair<int,int> entry : freq) {
maxFreq = max(maxFreq, entry.second);
}
// Create buckets based on frequencies
// Each bucket index represents frequency
vector<vector<int>> buckets(maxFreq + 1);
for (pair<int,int> entry : freq) {
buckets[entry.second].push_back(entry.first);
}
// Collect top k frequent elements
vector<int> res;
for (int i = maxFreq; i >= 1; --i) {
sort(buckets[i].begin(), buckets[i].end(),
greater<int>());
for (int num : buckets[i]) {
res.push_back(num);
if (res.size() == k) {
return res;
}
}
}
return res;
}
int main() {
vector<int> arr = { 3, 1, 4, 4, 5, 2, 6, 1 };
int k = 2;
vector<int> res = topKFrequent(arr, k);
for (int num : res)
cout << num << " ";
return 0;
}
Java
// Java program to find k most
// frequent element using counting sort
import java.util.*;
class GFG {
static ArrayList<Integer> topKFrequent(int[] arr, int k) {
// Count frequency of each element
HashMap<Integer, Integer> freq = new HashMap<>();
for (int num : arr) {
freq.put(num, freq.getOrDefault(num, 0) + 1);
}
// Find the maximum frequency
int maxFreq = 0;
for (Map.Entry<Integer, Integer> entry : freq.entrySet()) {
maxFreq = Math.max(maxFreq, entry.getValue());
}
// Create buckets based on frequencies
// Each bucket index represents frequency
ArrayList<ArrayList<Integer>> buckets = new ArrayList<>();
for (int i = 0; i <= maxFreq; i++) {
buckets.add(new ArrayList<>());
}
for (Map.Entry<Integer, Integer> entry : freq.entrySet()) {
buckets.get(entry.getValue()).add(entry.getKey());
}
// Collect top k frequent elements
ArrayList<Integer> res = new ArrayList<>();
for (int i = maxFreq; i >= 1; --i) {
Collections.sort(buckets.get(i), Collections.reverseOrder());
for (int num : buckets.get(i)) {
res.add(num);
if (res.size() == k) {
return res;
}
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {3, 1, 4, 4, 5, 2, 6, 1};
int k = 2;
ArrayList<Integer> res = topKFrequent(arr, k);
for (int num : res)
System.out.print(num + " ");
}
}
Python
# Python program to find k most
# frequent element using counting sort
def topKFrequent(arr, k):
# Count frequency of each element
freq = {}
for num in arr:
freq[num] = freq.get(num, 0) + 1
# Find the maximum frequency
maxFreq = max(freq.values())
# Create buckets based on frequencies
# Each bucket index represents frequency
buckets = [[] for _ in range(maxFreq + 1)]
for num, count in freq.items():
buckets[count].append(num)
# Collect top k frequent elements
res = []
for i in range(maxFreq, 0, -1):
buckets[i].sort(reverse=True)
for num in buckets[i]:
res.append(num)
if len(res) == k:
return res
return res
if __name__ == "__main__":
arr = [3, 1, 4, 4, 5, 2, 6, 1]
k = 2
res = topKFrequent(arr, k)
print(" ".join(map(str, res)))
C#
// C# program to find k most
// frequent element using counting sort
using System;
using System.Collections.Generic;
using System.Linq;
class GFG {
static List<int> topKFrequent(int[] arr, int k) {
// Count frequency of each element
Dictionary<int, int> freq = new Dictionary<int, int>();
foreach (int num in arr) {
if (!freq.ContainsKey(num))
freq[num] = 0;
freq[num]++;
}
// Find the maximum frequency
int maxFreq = freq.Values.Max();
// Create buckets based on frequencies
// Each bucket index represents frequency
List<List<int>> buckets = new List<List<int>>();
for (int i = 0; i <= maxFreq; i++)
buckets.Add(new List<int>());
foreach (var entry in freq)
buckets[entry.Value].Add(entry.Key);
// Collect top k frequent elements
List<int> res = new List<int>();
for (int i = maxFreq; i >= 1; --i) {
buckets[i].Sort((a, b) => b.CompareTo(a));
foreach (int num in buckets[i]) {
res.Add(num);
if (res.Count == k)
return res;
}
}
return res;
}
public static void Main() {
int[] arr = {3, 1, 4, 4, 5, 2, 6, 1};
int k = 2;
List<int> res = topKFrequent(arr, k);
foreach (int num in res)
Console.Write(num + " ");
}
}
JavaScript
// JavaScript program to find k most
// frequent element using counting sort
function topKFrequent(arr, k) {
// Count frequency of each element
let freq = new Map();
for (let num of arr) {
freq.set(num, (freq.get(num) || 0) + 1);
}
// Find the maximum frequency
let maxFreq = Math.max(...freq.values());
// Create buckets based on frequencies
// Each bucket index represents frequency
let buckets = Array.from({ length: maxFreq + 1 }, () => []);
for (let [num, count] of freq.entries()) {
buckets[count].push(num);
}
// Collect top k frequent elements
let res = [];
for (let i = maxFreq; i >= 1; --i) {
buckets[i].sort((a, b) => b - a);
for (let num of buckets[i]) {
res.push(num);
if (res.length === k) {
return res;
}
}
}
return res;
}
// Driver code
let arr = [3, 1, 4, 4, 5, 2, 6, 1];
let k = 2;
let res = topKFrequent(arr, k);
console.log(res.join(" "));
Time Complexity: O(n log n) where n is size of array
Auxiliary Space: O(n)
[Alternate Approach] Using Quick Select
In quick select we partition the array of unique numbers in such a way that the elements to the left of pivot are more frequent than pivot, and elements to the right of pivot are less frequent than pivot. Thus we can say the pivot is 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 pivot and each time we reduce our partitioning space w.r.t the pivot.
Partition Algorithm
Let's imagine the pivot at store point (j). If the ith element is more frequent than pivot, then the ith element will be on the left of pivot, but the store point (j) 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 (j) forward so that the more frequent element is on the left. If ith 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 store index.
C++
// C++ program to find k numbers with most
// occurrences in the given array using quick select.
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
int partition(int left, int right, int pivotIdx,
vector<int> &distinct, unordered_map<int, int> &mp) {
int pivotFreq = mp[distinct[pivotIdx]];
// Move the pivot to the end
swap(distinct[pivotIdx], distinct[right]);
// Move all less frequent elements to the left
int j = left;
for (int i = left; i <= right; i++) {
if (mp[distinct[i]] < pivotFreq) {
swap(distinct[j], distinct[i]);
j++;
}
}
// Move the pivot to its final place
swap(distinct[right], distinct[j]);
return j;
}
void quickselect(int left, int right, int k,
vector<int> &distinct, unordered_map<int, int> &mp) {
// base case: the list contains only one element
if (left == right) return;
int pivotIdx = left + rand() % (right - left + 1);
// Find the pivot position in a sorted list
pivotIdx = partition(left, right, pivotIdx, distinct, mp);
//If the pivot is in its final sorted position
if (pivotIdx == k) {
return;
} else if (pivotIdx > k) {
// go left
quickselect(left, pivotIdx - 1, k, distinct, mp);
} else {
// go right
quickselect(pivotIdx + 1, right, k, distinct, mp);
}
}
vector<int> topKFrequent(vector<int>& arr, int k) {
vector<int> distinct;
unordered_map<int, int> mp;
// Count frequency of each element
for (int val : arr) {
mp[val]++;
}
// array of unique elements
int n = mp.size();
for (pair<int, int> itr : mp) {
distinct.push_back(itr.first);
}
// kth top frequent element is (n - k)th less frequent.
quickselect(0, n - 1, n - k, distinct, mp);
// Return top k frequent elements
vector<int> res;
for (int i=n-k; i<n; ++i) {
res.push_back(distinct[i]);
}
return res;
}
int main() {
vector<int> arr{ 3, 1, 4, 4, 5, 2, 6, 1 };
int k = 2;
vector<int> res = topKFrequent(arr, k);
for (int val: res)
cout << val << " ";
return 0;
}
Java
// Java program to find k numbers with most
// occurrences in the given array using quick select.
import java.util.*;
class GfG {
static int partition(int left, int right, int pivotIdx,
ArrayList<Integer> distinct, HashMap<Integer, Integer> mp) {
int pivotFreq = mp.get(distinct.get(pivotIdx));
// Move the pivot to the end
Collections.swap(distinct, pivotIdx, right);
// Move all less frequent elements to the left
int j = left;
for (int i = left; i <= right; i++) {
if (mp.get(distinct.get(i)) < pivotFreq) {
Collections.swap(distinct, j, i);
j++;
}
}
// Move the pivot to its final place
Collections.swap(distinct, right, j);
return j;
}
static void quickselect(int left, int right, int k,
ArrayList<Integer> distinct, HashMap<Integer, Integer> mp) {
// Base case: the list contains only one element
if (left == right) return;
int pivotIdx = left + new Random().nextInt(right - left + 1);
// Find the pivot position in a sorted list
pivotIdx = partition(left, right, pivotIdx, distinct, mp);
// If the pivot is in its final sorted position
if (pivotIdx == k) {
return;
} else if (pivotIdx > k) {
// Go left
quickselect(left, pivotIdx - 1, k, distinct, mp);
} else {
// Go right
quickselect(pivotIdx + 1, right, k, distinct, mp);
}
}
static ArrayList<Integer> topKFrequent(int[] arr, int k) {
HashMap<Integer, Integer> mp = new HashMap<>();
ArrayList<Integer> distinct = new ArrayList<>();
// Count frequency of each element
for (int val : arr) {
mp.put(val, mp.getOrDefault(val, 0) + 1);
}
// Array of unique elements
int n = mp.size();
for (Map.Entry<Integer, Integer> entry : mp.entrySet()) {
distinct.add(entry.getKey());
}
// kth top frequent element is (n - k)th less frequent.
quickselect(0, n - 1, n - k, distinct, mp);
// Return top k frequent elements
ArrayList<Integer> res = new ArrayList<>();
for (int i = n - k; i < n; ++i) {
res.add(distinct.get(i));
}
return res;
}
public static void main(String[] args) {
int[] arr = {3, 1, 4, 4, 5, 2, 6, 1};
int k = 2;
ArrayList<Integer> res = topKFrequent(arr, k);
for (int val : res) {
System.out.print(val + " ");
}
}
}
Python
# Python program to find k numbers with most
# occurrences in the given array using quick select.
import random
def partition(left, right, pivotIdx, distinct, mp):
pivotFreq = mp[distinct[pivotIdx]]
# Move the pivot to the end
distinct[pivotIdx], distinct[right] = distinct[right], distinct[pivotIdx]
# Move all less frequent elements to the left
j = left
for i in range(left, right + 1):
if mp[distinct[i]] < pivotFreq:
distinct[j], distinct[i] = distinct[i], distinct[j]
j += 1
# Move the pivot to its final place
distinct[right], distinct[j] = distinct[j], distinct[right]
return j
def quickselect(left, right, k, distinct, mp):
# Base case: the list contains only one element
if left == right:
return
pivotIdx = left + random.randint(0, right - left)
# Find the pivot position in a sorted list
pivotIdx = partition(left, right, pivotIdx, distinct, mp)
# If the pivot is in its final sorted position
if pivotIdx == k:
return
elif pivotIdx > k:
# Go left
quickselect(left, pivotIdx - 1, k, distinct, mp)
else:
# Go right
quickselect(pivotIdx + 1, right, k, distinct, mp)
def topKFrequent(arr, k):
mp = {}
# Count frequency of each element
for val in arr:
mp[val] = mp.get(val, 0) + 1
# Array of unique elements
distinct = list(mp.keys())
# kth top frequent element is (n - k)th less frequent.
quickselect(0, len(distinct) - 1, len(distinct) - k, distinct, mp)
# Return top k frequent elements
return distinct[len(distinct) - k:]
if __name__ == "__main__":
arr = [3, 1, 4, 4, 5, 2, 6, 1]
k = 2
res = topKFrequent(arr, k)
print(" ".join(map(str, res)))
JavaScript
// JavaScript program to find k numbers with most
// occurrences in the given array using quick select.
function partition(left, right, pivotIdx, distinct, mp) {
let pivotFreq = mp.get(distinct[pivotIdx]);
// Move the pivot to the end
[distinct[pivotIdx], distinct[right]] = [distinct[right], distinct[pivotIdx]];
// Move all less frequent elements to the left
let j = left;
for (let i = left; i <= right; i++) {
if (mp.get(distinct[i]) < pivotFreq) {
[distinct[j], distinct[i]] = [distinct[i], distinct[j]];
j++;
}
}
// Move the pivot to its final place
[distinct[right], distinct[j]] = [distinct[j], distinct[right]];
return j;
}
function quickselect(left, right, k, distinct, mp) {
// Base case: the list contains only one element
if (left === right) return;
let pivotIdx = left + Math.floor(Math.random() * (right - left + 1));
// Find the pivot position in a sorted list
pivotIdx = partition(left, right, pivotIdx, distinct, mp);
// If the pivot is in its final sorted position
if (pivotIdx === k) {
return;
} else if (pivotIdx > k) {
// Go left
quickselect(left, pivotIdx - 1, k, distinct, mp);
} else {
// Go right
quickselect(pivotIdx + 1, right, k, distinct, mp);
}
}
function topKFrequent(arr, k) {
let mp = new Map();
// Count frequency of each element
for (let val of arr) {
mp.set(val, (mp.get(val) || 0) + 1);
}
// Array of unique elements
let distinct = [...mp.keys()];
let n = distinct.length;
// kth top frequent element is (n - k)th less frequent.
quickselect(0, n - 1, n - k, distinct, mp);
// Return top k frequent elements
return distinct.slice(n - k);
}
// Driver code
let arr = [3, 1, 4, 4, 5, 2, 6, 1];
let k = 2;
let res = topKFrequent(arr, k);
console.log(res.join(" "));
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)
Top K Frequent Elements in Array - I | DSA Problem
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem