Given Array of size n and a number k, find all elements that appear more than n/k times
Last Updated :
23 Jul, 2025
Given an array of size n and an integer k, find all elements in the array that appear more than n/k times.
Examples:
Input: arr[ ] = [3, 4, 2, 2, 1, 2, 3, 3], k = 4
Output: [2, 3]
Explanation: Here n/k is 8/4 = 2, therefore 2 appears 3 times in the array that is greater than 2 and 3 appears 3 times in the array that is greater than 2
Input: arr[ ] = [9, 10, 7, 9, 2, 9, 10], k = 3
Output: [9]
Explanation: Here n/k is 7/3 = 2, therefore 9 appears 3 times in the array that is greater than 2.
[Expected Solution] - Use Hashing - O(n) Time and O(n) Space
The idea is to pick all elements one by one. For every picked element, count its occurrences by traversing the array, if count becomes more than n/k, then print the element.
Follow the steps below to solve the problem:
- First, make a frequency map of all the elements in the array
- Then traverse the map and check the frequency of every element
- If the frequency is greater than n/k then print the element.
C++
#include <bits/stdc++.h>
using namespace std;
void morethanNbyK(vector<int> &arr, int k)
{
int n = arr.size();
int x = n / k;
// unordered_map initialization
unordered_map<int, int> freq;
for (int i = 0; i < n; i++)
{
freq[arr[i]]++;
}
// Traversing the map
for (auto i : freq)
{
// Checking if value of a key-value pair
// is greater than x (where x=n/k)
if (i.second > x)
{
// Print the key of whose value
// is greater than x
cout << i.first << endl;
}
}
}
// Driver Code
int main()
{
vector<int> arr = {3, 4, 2, 2, 1, 2, 3, 3};
int k = 4;
morethanNbyK(arr, k);
return 0;
}
Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void morethanNbyK(int[] arr, int k)
{
int n = arr.length;
int x = n / k;
// HashMap initialization
HashMap<Integer, Integer> freq = new HashMap<>();
for (int i = 0; i < n; i++) {
freq.put(arr[i],
freq.getOrDefault(arr[i], 0) + 1);
}
// Traversing the map
for (Map.Entry<Integer, Integer> entry :
freq.entrySet()) {
// Checking if value of a key-value pair
// is greater than x (where x=n/k)
if (entry.getValue() > x) {
// Print the key of whose value is greater
// than x
System.out.println(entry.getKey());
}
}
}
public static void main(String[] args)
{
int[] arr = { 3, 4, 2, 2, 1, 2, 3, 3 };
int k = 4;
morethanNbyK(arr, k);
}
}
Python
def morethanNbyK(arr, k):
n = len(arr)
x = n // k
# dictionary initialization
freq = {}
for num in arr:
freq[num] = freq.get(num, 0) + 1
# Sort the dictionary keys
sorted_keys = sorted(freq.keys())
# Traversing the sorted keys
for key in sorted_keys:
# Checking if value of a key-value pair is greater than x
if freq[key] > x:
# Print the key whose value is greater than x
print(key)
arr = [3, 4, 2, 2, 1, 2, 3, 3]
k = 4
morethanNbyK(arr, k)
C#
using System;
using System.Collections.Generic;
class Program {
public static void MoreThanNbyK(int[] arr, int k)
{
int n = arr.Length;
int x = n / k;
// Dictionary initialization
Dictionary<int, int> freq = new Dictionary<int, int>();
for (int i = 0; i < n; i++) {
if (freq.ContainsKey(arr[i])) {
freq[arr[i]]++;
}
else {
freq[arr[i]] = 1;
}
}
// Sort the dictionary keys
List<int> keys = new List<int>(freq.Keys);
keys.Sort();
// Traversing the sorted keys
foreach (var key in keys)
{
// Checking if the frequency of the element is greater than x (where x=n/k)
if (freq[key] > x) {
// Print the key whose value is greater than x
Console.WriteLine(key);
}
}
}
static void Main()
{
int[] arr = { 3, 4, 2, 2, 1, 2, 3, 3 };
int k = 4;
MoreThanNbyK(arr, k);
}
}
JavaScript
function morethanNbyK(arr, k)
{
const n = arr.length;
const x = Math.floor(n / k);
// object initialization
const freq = {};
for (let i = 0; i < n; i++) {
freq[arr[i]] = (freq[arr[i]] || 0) + 1;
}
// Traversing the object
for (const key in freq) {
// Checking if value of a key-value pair
// is greater than x (where x=n/k)
if (freq[key] > x) {
// Print the key of whose value is greater than
// x
console.log(key);
}
}
}
// Driver Code
const arr = [ 3, 4, 2, 2, 1, 2, 3, 3 ];
const k = 4;
morethanNbyK(arr, k);
[Expected Solution for Small K] - Moore's Voting Algorithm - O(n x k) Time and O(k) Space
The idea is to apply Moore's Voting algorithm, as there can be at max k - 1 elements present in the array which appears more than n/k times so their will be k - 1 candidates. When we encounter an element which is one of our candidates then increment the count else decrement the count.
Illustration:
Consider k = 4, n = 9
Given array: 3 1 2 2 2 1 4 3 3
i = 0
temp[] has one element {3} with count 1
i = 1
temp[] has two elements {3, 1} with counts 1 and 1 respectively
i = 2
temp[] has three elements, {3, 1, 2} with counts as 1, 1 and 1 respectively.
i = 3
temp[] has three elements, {3, 1, 2} with counts as 1, 1 and 2 respectively.
i = 4
temp[] has three elements, {3, 1, 2} with counts as 1, 1 and 3 respectively.
i = 5
temp[] has three elements, {3, 1, 2 with counts as 1, 2 and 3 respectively.
i = 6
temp[] has two elements, {1, 2} with counts as 1 and 2 respectively.
i = 7
temp[] has three elements, {3, 1, 2} with counts as 1, 1 and 2 respectively.
i = 8
temp[] has three elements, {3, 1, 2} with counts as 2, 1 and 2 respectively.
Follow the steps below to solve the problem:
- Create a temporary array of size (k - 1) to store elements and their counts (The output elements are going to be among these k-1 elements).
- Traverse through the input array and update temp[] (add/remove an element or increase/decrease count) for every traversed element. The array temp[] stores potential (k-1) candidates at every step.
- Iterate through final (k-1) potential candidates (stored in temp[]). or every element, check if it actually has counted of more than n/k.
C++
#include <iostream>
#include <vector>
using namespace std;
// A structure to store an element and its current count
struct eleCount
{
int e; // Element
int c; // Count
};
// Prints elements with more
// than n/k occurrences in arr[]
// of size n. If there are no
// such elements, then it prints
// nothing.
void moreThanNdK(vector<int> &arr, int k)
{
int n = arr.size();
// k must be greater than
// 1 to get some output
if (k < 2)
return;
/* Step 1: Create a temporary
array (contains element
and count) of size k-1.
Initialize count of all
elements as 0 */
vector<eleCount> temp(k - 1);
for (int i = 0; i < k - 1; i++)
temp[i].c = 0, temp[i].e = -1;
/* Step 2: Process all
elements of input array */
for (int i = 0; i < n; i++)
{
int j;
/* If arr[i] is already present in
the element count array,
then increment its count
*/
for (j = 0; j < k - 1; j++)
{
if (temp[j].e == arr[i])
{
temp[j].c += 1;
break;
}
}
/* If arr[i] is not present in temp[] */
if (j == k - 1)
{
int l;
/* If there is position available
in temp[], then place arr[i] in
the first available position and
set count as 1*/
for (l = 0; l < k - 1; l++)
{
if (temp[l].c == 0)
{
temp[l].e = arr[i];
temp[l].c = 1;
break;
}
}
/* If all the position in the
temp[] are filled, then decrease
count of every element by 1 */
if (l == k - 1)
for (l = 0; l < k - 1; l++)
temp[l].c -= 1;
}
}
/*Step 3: Check actual counts of
* potential candidates in temp[]*/
for (int i = 0; i < k - 1; i++)
{
// Calculate actual count of elements
int ac = 0; // actual count
for (int j = 0; j < n; j++)
if (arr[j] == temp[i].e)
ac++;
// If actual count is more than n/k,
// then print it
if (ac > n / k)
cout << "Number:" << temp[i].e << " Count:" << ac << endl;
}
}
int main()
{
vector<int> arr = {3, 4, 2, 2, 1, 2, 3, 3};
int k = 4;
moreThanNdK(arr, k);
return 0;
}
Java
// A structure to store an element and its current count
class EleCount {
int e; // Element
int c; // Count
}
public class Main {
// Prints elements with more than n/k occurrences in
// arr[] of size n. If there are no such elements, then
// it prints nothing.
public static void moreThanNdK(int[] arr, int k)
{
int n = arr.length;
// k must be greater than 1 to get some output
if (k < 2)
return;
// Step 1: Create a temporary array (contains
// element and count) of size k-1. Initialize count
// of all elements as 0
EleCount[] temp = new EleCount[k - 1];
for (int i = 0; i < k - 1; i++) {
temp[i] = new EleCount();
temp[i].c = 0;
temp[i].e = -1;
}
// Step 2: Process all elements of input array
for (int i = 0; i < n; i++) {
int j;
// If arr[i] is already present in the element
// count array, then increment its count
for (j = 0; j < k - 1; j++) {
if (temp[j].e == arr[i]) {
temp[j].c += 1;
break;
}
}
// If arr[i] is not present in temp[]
if (j == k - 1) {
int l;
// If there is position available in temp[],
// then place arr[i] in the first available
// position and set count as 1
for (l = 0; l < k - 1; l++) {
if (temp[l].c == 0) {
temp[l].e = arr[i];
temp[l].c = 1;
break;
}
}
// If all the position in the temp[] are
// filled, then decrease count of every
// element by 1
if (l == k - 1) {
for (l = 0; l < k - 1; l++) {
temp[l].c -= 1;
}
}
}
}
// Step 3: Check actual counts of potential
// candidates in temp[]
for (int i = 0; i < k - 1; i++) {
// Calculate actual count of elements
int ac = 0; // actual count
for (int j = 0; j < n; j++) {
if (arr[j] == temp[i].e)
ac++;
}
// If actual count is more than n/k, then print
// it
if (ac > n / k) {
System.out.println("Number: " + temp[i].e
+ " Count: " + ac);
}
}
}
// Driver code
public static void main(String[] args)
{
int[] arr = { 3, 4, 2, 2, 1, 2, 3, 3 };
int k = 4;
moreThanNdK(arr, k);
}
}
Python
# A structure to store an element and its current count
class EleCount:
def __init__(self):
self.e = -1 # Element
self.c = 0 # Count
def moreThanNdK(arr, k):
n = len(arr)
# k must be greater than 1 to get some output
if k < 2:
return
# Step 1: Create a temporary array (contains
# element and count) of size k-1. Initialize count
# of all elements as 0
temp = [EleCount() for _ in range(k - 1)]
# Step 2: Process all elements of input array
for i in range(n):
j = 0
# If arr[i] is already present in the element
# count array, then increment its count
while j < k - 1:
if temp[j].e == arr[i]:
temp[j].c += 1
break
j += 1
# If arr[i] is not present in temp[]
if j == k - 1:
l = 0
# If there is position available in temp[],
# then place arr[i] in the first available
# position and set count as 1
while l < k - 1:
if temp[l].c == 0:
temp[l].e = arr[i]
temp[l].c = 1
break
l += 1
# If all the positions in temp[] are filled,
# then decrease count of every element by 1
if l == k - 1:
for l in range(k - 1):
temp[l].c -= 1
# Step 3: Check actual counts of potential
# candidates in temp[]
for i in range(k - 1):
ac = 0 # actual count
for j in range(n):
if arr[j] == temp[i].e:
ac += 1
# If actual count is more than n/k, then print
# it
if ac > n // k:
print(f"Number: {temp[i].e} Count: {ac}")
if __name__ == "__main__":
arr = [3, 4, 2, 2, 1, 2, 3, 3]
k = 4
moreThanNdK(arr, k)
C#
using System;
class EleCount {
public int e; // Element
public int c; // Count
}
class MainClass {
// Prints elements with more than n/k occurrences in
// arr[] of size n. If there are no such elements, then
// it prints nothing.
public static void MoreThanNdK(int[] arr, int k)
{
int n = arr.Length;
// k must be greater than 1 to get some output
if (k < 2)
return;
// Step 1: Create a temporary array (contains
// element and count) of size k-1. Initialize count
// of all elements as 0
EleCount[] temp = new EleCount[k - 1];
for (int i = 0; i < k - 1; i++) {
temp[i] = new EleCount();
temp[i].c = 0;
temp[i].e = -1;
}
// Step 2: Process all elements of input array
for (int i = 0; i < n; i++) {
int j;
// If arr[i] is already present in the element
// count array, then increment its count
for (j = 0; j < k - 1; j++) {
if (temp[j].e == arr[i]) {
temp[j].c += 1;
break;
}
}
// If arr[i] is not present in temp[]
if (j == k - 1) {
int l;
// If there is position available in temp[],
// then place arr[i] in the first available
// position and set count as 1
for (l = 0; l < k - 1; l++) {
if (temp[l].c == 0) {
temp[l].e = arr[i];
temp[l].c = 1;
break;
}
}
// If all the position in the temp[] are
// filled, then decrease count of every
// element by 1
if (l == k - 1) {
for (l = 0; l < k - 1; l++) {
temp[l].c -= 1;
}
}
}
}
// Step 3: Check actual counts of potential
// candidates in temp[]
for (int i = 0; i < k - 1; i++) {
// Calculate actual count of elements
int ac = 0; // actual count
for (int j = 0; j < n; j++) {
if (arr[j] == temp[i].e)
ac++;
}
// If actual count is more than n/k, then print
// it
if (ac > n / k) {
Console.WriteLine("Number: " + temp[i].e
+ " Count: " + ac);
}
}
}
public static void Main(string[] args)
{
int[] arr = { 3, 4, 2, 2, 1, 2, 3, 3 };
int k = 4;
MoreThanNdK(arr, k);
}
}
JavaScript
// A structure to store an element and its current count
class EleCount {
constructor(e)
{
this.e = e; // Element
this.c = 0; // Count
}
}
// Prints elements with more
// than n/k occurrences in arr[]
// of size n. If there are no
// such elements, then it prints
// nothing.
function moreThanNdK(arr, k)
{
const n = arr.length;
// k must be greater than
// 1 to get some output
if (k < 2)
return;
/* Step 1: Create a temporary
array (contains element
and count) of size k-1.
Initialize count of all
elements as 0 */
const temp = Array.from({length : k - 1},
() => new EleCount(-1));
/* Step 2: Process all
elements of input array */
for (let i = 0; i < n; i++) {
let j;
/* If arr[i] is already present in
the element count array,
then increment its count
*/
for (j = 0; j < k - 1; j++) {
if (temp[j].e === arr[i]) {
temp[j].c += 1;
break;
}
}
/* If arr[i] is not present in temp[] */
if (j === k - 1) {
let l;
/* If there is position available
in temp[], then place arr[i] in
the first available position and
set count as 1*/
for (l = 0; l < k - 1; l++) {
if (temp[l].c === 0) {
temp[l].e = arr[i];
temp[l].c = 1;
break;
}
}
/* If all the position in the
temp[] are filled, then decrease
count of every element by 1 */
if (l === k - 1) {
for (l = 0; l < k - 1; l++) {
temp[l].c -= 1;
}
}
}
}
/*Step 3: Check actual counts of
* potential candidates in temp[]*/
for (let i = 0; i < k - 1; i++) {
// Calculate actual count of elements
let ac = 0; // actual count
for (let j = 0; j < n; j++) {
if (arr[j] === temp[i].e)
ac++;
}
// If actual count is more than n/k,
// then print it
if (ac > n / k) {
console.log(
`Number: ${temp[i].e} Count: ${ac}`);
}
}
}
/* Driver code */
const arr = [ 3, 4, 2, 2, 1, 2, 3, 3 ];
const k = 4;
moreThanNdK(arr, k);
OutputNumber:3 Count:3
Number:2 Count:3
Time Complexity: O(n * k), Checking for each element of the array(size N) in the candidate array of size K
Auxiliary Space: O(k) Space required to store the candidates.
Using Built-In Counter in Python
This approach is same the first approach but here in python there is a counter() that calculates the frequency array.
- Count the frequencies of every element using Counter() function.
- Traverse the frequency array and print all the elements which occur at more than n/k times.
Python
# Python3 implementation
from collections import Counter
# Function to find the number of array
# elements with frequency more than 1/k times
def printElements(arr, k):
# Counting frequency of every
# element using Counter
mp = Counter(arr)
# Traverse the map and print all
# the elements with occurrence
# more than 1/k times
for it in mp:
if mp[it] > len(arr) // k:
print(it)
# Driver code
if __name__ == '__main__':
arr = [3, 4, 2, 2, 1, 2, 3, 3]
k = 4
printElements(arr, k)
Count More than n/k Occurences | 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