Majority Element II – Elements occurring more than ⌊N/3⌋ times
Last Updated :
23 Oct, 2024
Given an array arr[] consisting of n integers, the task is to find all the array elements which occurs more than floor(n/3) times.
Note: The returned array of majority elements should be sorted.
Examples:
Input: arr[] = {2, 2, 3, 1, 3, 2, 1, 1}
Output: {1, 2}
Explanation: The frequency of 1 and 2 is 3, which is more than floor n/3 (8/3 = 2).
Input: arr[] = {-5, 3, -5}
Output: {-5}
Explanation: The frequency of -5 is 2, which is more than floor n/3 (3/3 = 1).
Input: arr[] = {3, 2, 2, 4, 1, 4}
Output: { }
Explanation: There is no majority element.
[Naive Approach] Using Nested Loops – O(n^2) Time and O(1) Space
The idea is to iterate over all elements and count the frequency of the element in the array. If the frequency of the element is greater than floor(n/3), add it to the result. To avoid adding duplicate elements into the result, we can check if the element is already present in the result. We can stop the iteration if we have already found two majority elements.
C++
// C++ program to find Majority elements in an array
// using nested loops
#include <iostream>
#include <vector>
using namespace std;
// Function to find Majority elements in an array
vector<int> findMajority(vector<int> &arr) {
int n = arr.size();
vector<int> res;
for (int i = 0; i < n; i++) {
// Count the frequency of arr[i]
int cnt = 0;
for (int j = i; j < n; j++) {
if (arr[j] == arr[i])
cnt += 1;
}
// Check if arr[i] is a majority element
if (cnt > (n / 3)) {
// Add arr[i] only if it is not already
// present in the result
if (res.size() == 0 || arr[i] != res[0]) {
res.push_back(arr[i]);
}
}
// If we have found two majority elements,
// we can stop our search
if (res.size() == 2) {
if(res[0] > res[1])
swap(res[0], res[1]);
break;
}
}
return res;
}
int main() {
vector<int> arr = {2, 2, 3, 1, 3, 2, 1, 1};
vector<int> res = findMajority(arr);
for (int ele : res)
cout << ele << " ";
return 0;
}
C
// C program to find Majority element in an array
// using nested loop
#include <stdio.h>
int *findMajority(int *arr, int n, int *resSize) {
int *res = (int *)malloc(2 * sizeof(int));
*resSize = 0;
for (int i = 0; i < n; i++) {
// Count the frequency of arr[i]
int cnt = 0;
for (int j = i; j < n; j++) {
if (arr[j] == arr[i])
cnt += 1;
}
// Check if arr[i] is a majority element
if (cnt > (n / 3)) {
// Add arr[i] only if it is not already
// present in the result
if (*resSize == 0 || arr[i] != res[0]) {
res[*resSize] = arr[i];
(*resSize)++;
}
}
// If we have found two majority elements,
// we can stop our search
if (*resSize == 2) {
if (res[0] > res[1]) {
int temp = res[0];
res[0] = res[1];
res[1] = temp;
}
break;
}
}
return res;
}
int main() {
int arr[] = {2, 2, 3, 1, 3, 2, 1, 1};
int n = sizeof(arr) / sizeof(arr[0]);
int resSize;
int *res = findMajority(arr, n, &resSize);
for (int i = 0; i < resSize; i++)
printf("%d ", res[i]);
return 0;
}
Java
// Java program to find Majority element in an array
// using nested loop
import java.util.ArrayList;
import java.util.List;
class GfG {
// Function to find Majority elements in an array
static List<Integer> findMajority(int[] arr) {
int n = arr.length;
List<Integer> res = new ArrayList<>();
for (int i = 0; i < n; i++) {
// Count the frequency of arr[i]
int cnt = 0;
for (int j = i; j < n; j++) {
if (arr[j] == arr[i])
cnt += 1;
}
// Check if arr[i] is a majority element
if (cnt > (n / 3)) {
// Add arr[i] only if it is not already
// present in the result
if (res.size() == 0 || arr[i] != res.get(0)) {
res.add(arr[i]);
}
}
// If we have found two majority elements,
// we can stop our search
if (res.size() == 2) {
if (res.get(0) > res.get(1))
java.util.Collections.swap(res, 0, 1);
break;
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {2, 2, 3, 1, 3, 2, 1, 1};
List<Integer> res = findMajority(arr);
for (int ele : res)
System.out.print(ele + " ");
}
}
Python
# Python program to find Majority elements in an array
# using nested loops
def findMajority(arr):
n = len(arr)
res = []
for i in range(n):
# Count the frequency of arr[i]
cnt = 0
for j in range(i, n):
if arr[j] == arr[i]:
cnt += 1
# Check if arr[i] is a majority element
if cnt > (n // 3):
# Add arr[i] only if it is not already
# present in the result
if len(res) == 0 or arr[i] != res[0]:
res.append(arr[i])
# If we have found two majority elements,
# we can stop our search
if len(res) == 2:
if res[0] > res[1]:
res[0], res[1] = res[1], res[0]
break
return res
if __name__ == "__main__":
arr = [2, 2, 3, 1, 3, 2, 1, 1]
res = findMajority(arr)
for ele in res:
print(ele, end=" ")
C#
// C# program to find Majority element in an array
// using nested loop
using System;
using System.Collections.Generic;
class GfG {
// Function to find Majority elements in an array
static List<int> findMajority(int[] arr) {
int n = arr.Length;
List<int> res = new List<int>();
for (int i = 0; i < n; i++) {
// Count the frequency of arr[i]
int cnt = 0;
for (int j = i; j < n; j++) {
if (arr[j] == arr[i])
cnt += 1;
}
// Check if arr[i] is a majority element
if (cnt > (n / 3)) {
// Add arr[i] only if it is not already
// present in the result
if (res.Count == 0 || arr[i] != res[0]) {
res.Add(arr[i]);
}
}
// If we have found two majority elements,
// we can stop our search
if (res.Count == 2) {
if (res[0] > res[1]) {
int temp = res[0];
res[0] = res[1];
res[1] = temp;
}
break;
}
}
return res;
}
static void Main(string[] args) {
int[] arr = { 2, 2, 3, 1, 3, 2, 1, 1 };
List<int> res = findMajority(arr);
foreach (int ele in res)
Console.Write(ele + " ");
}
}
JavaScript
// JavaScript program to find Majority elements in an array
// using nested loops
function findMajority(arr) {
const n = arr.length;
const res = [];
for (let i = 0; i < n; i++) {
// Count the frequency of arr[i]
let cnt = 0;
for (let j = i; j < n; j++) {
if (arr[j] === arr[i]) {
cnt += 1;
}
}
// Check if arr[i] is a majority element
if (cnt > (n / 3)) {
// Add arr[i] only if it is not already
// present in the result
if (res.length === 0 || arr[i] !== res[0]) {
res.push(arr[i]);
}
}
// If we have found two majority elements,
// we can stop our search
if (res.length === 2) {
if (res[0] > res[1]) {
[res[0], res[1]] = [res[1], res[0]];
}
break;
}
}
return res;
}
const arr = [2, 2, 3, 1, 3, 2, 1, 1];
const res = findMajority(arr);
console.log(res.join(" "));
[Better Approach] Using Hash Map or Dictionary – O(n) Time and O(n) Space
The idea is to use a hash map or dictionary to count the frequency of each element in the array. After counting, iterate over the hash map and if the frequency of any element is greater than (n/3), push it into the result. Finally, the majority elements are returned after sorting.
C++
// C++ program for finding out majority element in an array
// using hash map
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
// Function to find Majority element in an array
vector<int> findMajority(vector<int> &arr) {
int n = arr.size();
unordered_map<int, int> freq;
vector<int> res;
// find frequency of each number
for (int ele : arr)
freq[ele]++;
// Iterate over each key-value pair in the hash map
for (auto it : freq) {
int ele = it.first;
int cnt = it.second;
// Add the element to the result, if its frequency
// if greater than floor(n/3)
if (cnt > n / 3)
res.push_back(ele);
}
if (res.size() == 2 && res[0] > res[1])
swap(res[0], res[1]);
return res;
}
int main() {
vector<int> arr = {2, 2, 3, 1, 3, 2, 1, 1};
vector<int> res = findMajority(arr);
for (auto ele : res) {
cout << ele << " ";
}
return 0;
}
Java
// Java program for finding out majority element in an array
// using hash map
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
class GfG {
// Function to find Majority element in an array
static List<Integer> findMajority(int[] arr) {
int n = arr.length;
HashMap<Integer, Integer> freq = new HashMap<>();
List<Integer> res = new ArrayList<>();
// find frequency of each number
for (int ele : arr)
freq.put(ele, freq.getOrDefault(ele, 0) + 1);
// Iterate over each key-value pair in the hash map
for (Map.Entry<Integer, Integer> it : freq.entrySet()) {
int ele = it.getKey();
int cnt = it.getValue();
// Add the element to the result, if its frequency
// if greater than floor(n/3)
if (cnt > n / 3)
res.add(ele);
}
if (res.size() == 2 && res.get(0) > res.get(1)) {
int temp = res.get(0);
res.set(0, res.get(1));
res.set(1, temp);
}
return res;
}
public static void main(String[] args) {
int[] arr = {2, 2, 3, 1, 3, 2, 1, 1};
List<Integer> res = findMajority(arr);
for (int ele : res) {
System.out.print(ele + " ");
}
}
}
Python
# Python program for finding out majority element in an array
# using hash map
def findMajority(arr):
n = len(arr)
freq = {}
res = []
# find frequency of each number
for ele in arr:
freq[ele] = freq.get(ele, 0) + 1
# Iterate over each key-value pair in the hash map
for ele, cnt in freq.items():
# Add the element to the result, if its frequency
# is greater than floor(n/3)
if cnt > n // 3:
res.append(ele)
if len(res) == 2 and res[0] > res[1]:
res[0], res[1] = res[1], res[0]
return res
if __name__ == "__main__":
arr = [2, 2, 3, 1, 3, 2, 1, 1]
res = findMajority(arr)
for ele in res:
print(ele, end=" ")
C#
// C# program for finding out majority element in an array
// using hash map
using System;
using System.Collections.Generic;
class GfG {
// Function to find Majority element in an array
static List<int> findMajority(int[] arr) {
int n = arr.Length;
Dictionary<int, int> freq = new Dictionary<int, int>();
List<int> res = new List<int>();
// find frequency of each number
foreach (int ele in arr) {
if (freq.ContainsKey(ele))
freq[ele]++;
else
freq[ele] = 1;
}
// Iterate over each key-value pair in the hash map
foreach (var it in freq) {
int ele = it.Key;
int cnt = it.Value;
// Add the element to the result, if its frequency
// is greater than floor(n/3)
if (cnt > n / 3)
res.Add(ele);
}
if (res.Count == 2 && res[0] > res[1]) {
int temp = res[0];
res[0] = res[1];
res[1] = temp;
}
return res;
}
static void Main() {
int[] arr = { 2, 2, 3, 1, 3, 2, 1, 1 };
List<int> res = findMajority(arr);
foreach (int ele in res) {
Console.Write(ele + " ");
}
}
}
JavaScript
// JavaScript program for finding out majority element in an array
// using hash map
function findMajority(arr) {
const n = arr.length;
const freq = {};
const res = [];
// find frequency of each number
for (const ele of arr) {
freq[ele] = (freq[ele] || 0) + 1;
}
// Iterate over each key-value pair in the hash map
for (const it in freq) {
const ele = Number(it);
const cnt = freq[it];
// Add the element to the result, if its frequency
// is greater than floor(n/3)
if (cnt > Math.floor(n / 3)) {
res.push(ele);
}
}
if (res.length === 2 && res[0] > res[1]) {
[res[0], res[1]] = [res[1], res[0]];
}
return res;
}
const arr = [2, 2, 3, 1, 3, 2, 1, 1];
const res = findMajority(arr);
console.log(res.join(" "));
[Expected Approach] Boyer-Moore’s Voting Algorithm – O(n) Time and O(1) Space
The idea is based on the observation that there can be at most two majority elements, which appear more than n/3 times. so we can use Boyer-Moore’s Voting algorithm. As we iterate the array, We identify potential majority elements by keeping track of two candidates and their respective counts.
Steps:
- Initialize two variables ele1 = -1 and ele2 = -1, for candidates and two variables cnt1 = 0 and cnt2 = 0, for counting.
- In each iteration,
- If an element is equal to any candidate, update that candidate’s count.
- If count of a candidate reaches zero then replace that candidate with current element.
- If neither candidate matches and both counts are non zero, decrement the counts.
- After this, in second pass we check if the chosen candidates appear more than n/3 times in the array. If they do then include them in result array.
Since any element than appears more than floor(n/3) times, will dominate over elements that appear less frequently. Whenever we encounter a different element, we decrement the count of both the candidates. This maintains at most two candidates in the array.
C++
// C++ program for finding the majority element in an array
// using Moore’s Voting algorithm
#include <iostream>
#include <vector>
#include <algorithm>
#include <limits.h>
using namespace std;
// Function to find Majority element in an array
vector<int> findMajority(vector<int> &arr) {
int n = arr.size();
// Initialize two candidates and their counts
int ele1 = -1, ele2 = -1, cnt1 = 0, cnt2 = 0;
for (int ele : arr) {
// Increment count for candidate 1
if (ele1 == ele) {
cnt1++;
}
// Increment count for candidate 2
else if (ele2 == ele) {
cnt2++;
}
// New candidate 1 if count is zero
else if (cnt1 == 0) {
ele1 = ele;
cnt1++;
}
// New candidate 2 if count is zero
else if (cnt2 == 0) {
ele2 = ele;
cnt2++;
}
// Decrease counts if neither candidate
else {
cnt1--;
cnt2--;
}
}
vector<int> res;
cnt1 = 0;
cnt2 = 0;
// Count the occurrences of candidates
for (int ele : arr) {
if (ele1 == ele) cnt1++;
if (ele2 == ele) cnt2++;
}
// Add to result if they are majority elements
if (cnt1 > n / 3) res.push_back(ele1);
if (cnt2 > n / 3 && ele1 != ele2) res.push_back(ele2);
if(res.size() == 2 && res[0] > res[1])
swap(res[0], res[1]);
return res;
}
int main() {
vector<int> arr = {2, 2, 3, 1, 3, 2, 1, 1};
vector<int> res = findMajority(arr);
for (int ele : res) {
cout << ele << " ";
}
return 0;
}
C
// C program for finding the majority element in an array
// using Moore’s Voting algorithm
#include <stdio.h>
#include <limits.h>
void findMajority(int arr[], int n, int *res, int *resSize) {
// Initialize two candidates and their counts
int ele1 = -1, ele2 = -1, cnt1 = 0, cnt2 = 0;
for (int i = 0; i < n; i++) {
int ele = arr[i];
// Increment count for candidate 1
if (ele1 == ele) {
cnt1++;
}
// Increment count for candidate 2
else if (ele2 == ele) {
cnt2++;
}
// New candidate 1 if count is zero
else if (cnt1 == 0) {
ele1 = ele;
cnt1++;
}
// New candidate 2 if count is zero
else if (cnt2 == 0) {
ele2 = ele;
cnt2++;
}
// Decrease counts if neither candidate
else {
cnt1--;
cnt2--;
}
}
cnt1 = 0;
cnt2 = 0;
// Count the occurrences of candidates
for (int i = 0; i < n; i++) {
int ele = arr[i];
if (ele1 == ele) cnt1++;
if (ele2 == ele) cnt2++;
}
// Add to result if they are majority elements
*resSize = 0;
if (cnt1 > n / 3) res[(*resSize)++] = ele1;
if (cnt2 > n / 3 && ele1 != ele2) res[(*resSize)++] = ele2;
// Sort the result if there are two elements
if (*resSize == 2 && res[0] > res[1]) {
int temp = res[0];
res[0] = res[1];
res[1] = temp;
}
}
int main() {
int arr[] = {2, 2, 3, 1, 3, 2, 1, 1};
int n = sizeof(arr) / sizeof(arr[0]);
int res[2];
int resSize;
findMajority(arr, n, res, &resSize);
for (int i = 0; i < resSize; i++) {
printf("%d ", res[i]);
}
return 0;
}
Java
// Java program for finding the majority element in an array
// using Moore’s Voting algorithm
import java.util.ArrayList;
import java.util.List;
class GfG {
// Function to find Majority element in an array
static List<Integer> findMajority(int[] arr) {
int n = arr.length;
// Initialize two candidates and their counts
int ele1 = -1, ele2 = -1;
int cnt1 = 0, cnt2 = 0;
for (int ele : arr) {
// Increment count for candidate 1
if (ele1 == ele) {
cnt1++;
}
// Increment count for candidate 2
else if (ele2 == ele) {
cnt2++;
}
// New candidate 1 if count is zero
else if (cnt1 == 0) {
ele1 = ele;
cnt1++;
}
// New candidate 2 if count is zero
else if (cnt2 == 0) {
ele2 = ele;
cnt2++;
}
// Decrease counts if neither candidate
else {
cnt1--;
cnt2--;
}
}
List<Integer> res = new ArrayList<>();
cnt1 = 0;
cnt2 = 0;
// Count the occurrences of candidates
for (int ele : arr) {
if (ele1 == ele) cnt1++;
if (ele2 == ele) cnt2++;
}
// Add to result if they are majority elements
if (cnt1 > n / 3) res.add(ele1);
if (cnt2 > n / 3 && ele1 != ele2) res.add(ele2);
if (res.size() == 2 && res.get(0) > res.get(1)) {
int temp = res.get(0);
res.set(0, res.get(1));
res.set(1, temp);
}
return res;
}
public static void main(String[] args) {
int[] arr = {2, 2, 3, 1, 3, 2, 1, 1};
List<Integer> res = findMajority(arr);
for (int ele : res) {
System.out.print(ele + " ");
}
}
}
Python
# Python program for finding the majority element in
# an array using Moore’s Voting algorithm
def findMajority(arr):
n = len(arr)
# Initialize two candidates and their counts
ele1, ele2 = -1, -1
cnt1, cnt2 = 0, 0
for ele in arr:
# Increment count for candidate 1
if ele1 == ele:
cnt1 += 1
# Increment count for candidate 2
elif ele2 == ele:
cnt2 += 1
# New candidate 1 if count is zero
elif cnt1 == 0:
ele1 = ele
cnt1 += 1
# New candidate 2 if count is zero
elif cnt2 == 0:
ele2 = ele
cnt2 += 1
# Decrease counts if neither candidate
else:
cnt1 -= 1
cnt2 -= 1
res = []
cnt1, cnt2 = 0, 0
# Count the occurrences of candidates
for ele in arr:
if ele1 == ele:
cnt1 += 1
if ele2 == ele:
cnt2 += 1
# Add to result if they are majority elements
if cnt1 > n / 3:
res.append(ele1)
if cnt2 > n / 3 and ele1 != ele2:
res.append(ele2)
if len(res) == 2 and res[0] > res[1]:
res[0], res[1] = res[1], res[0]
return res
if __name__ == "__main__":
arr = [2, 2, 3, 1, 3, 2, 1, 1]
res = findMajority(arr)
for ele in res:
print(ele, end=" ")
C#
// C# program for finding the majority element in an array
// using Moore’s Voting algorithm
using System;
using System.Collections.Generic;
class GfG {
// Function to find Majority element in an array
static List<int> FindMajority(int[] arr) {
int n = arr.Length;
// Initialize two candidates and their counts
int ele1 = -1, ele2 = -1, cnt1 = 0, cnt2 = 0;
foreach (int ele in arr) {
// Increment count for candidate 1
if (ele1 == ele) {
cnt1++;
}
// Increment count for candidate 2
else if (ele2 == ele) {
cnt2++;
}
// New candidate 1 if count is zero
else if (cnt1 == 0) {
ele1 = ele;
cnt1++;
}
// New candidate 2 if count is zero
else if (cnt2 == 0) {
ele2 = ele;
cnt2++;
}
// Decrease counts if neither candidate
else {
cnt1--;
cnt2--;
}
}
List<int> res = new List<int>();
cnt1 = 0;
cnt2 = 0;
// Count the occurrences of candidates
foreach (int ele in arr) {
if (ele1 == ele) cnt1++;
if (ele2 == ele) cnt2++;
}
// Add to result if they are majority elements
if (cnt1 > n / 3) res.Add(ele1);
if (cnt2 > n / 3 && ele1 != ele2) res.Add(ele2);
if (res.Count == 2 && res[0] > res[1]) {
int temp = res[0];
res[0] = res[1];
res[1] = temp;
}
return res;
}
static void Main() {
int[] arr = { 2, 2, 3, 1, 3, 2, 1, 1 };
List<int> res = FindMajority(arr);
foreach (int ele in res) {
Console.Write(ele + " ");
}
}
}
JavaScript
// JavaScript program for finding the majority element in an array
// using Moore’s Voting algorithm
function findMajority(arr) {
const n = arr.length;
// Initialize two candidates and their counts
let ele1 = -1, ele2 = -1;
let cnt1 = 0, cnt2 = 0;
for (let ele of arr) {
// Increment count for candidate 1
if (ele1 === ele) {
cnt1++;
}
// Increment count for candidate 2
else if (ele2 === ele) {
cnt2++;
}
// New candidate 1 if count is zero
else if (cnt1 === 0) {
ele1 = ele;
cnt1++;
}
// New candidate 2 if count is zero
else if (cnt2 === 0) {
ele2 = ele;
cnt2++;
}
// Decrease counts if neither candidate
else {
cnt1--;
cnt2--;
}
}
const res = [];
cnt1 = 0;
cnt2 = 0;
// Count the occurrences of candidates
for (let ele of arr) {
if (ele1 === ele) cnt1++;
if (ele2 === ele) cnt2++;
}
// Add to result if they are majority elements
if (cnt1 > n / 3) res.push(ele1);
if (cnt2 > n / 3 && ele1 != ele2) res.push(ele2);
if (res.length === 2 && res[0] > res[1]) {
[res[0], res[1]] = [res[1], res[0]];
}
return res;
}
const arr = [2, 2, 3, 1, 3, 2, 1, 1];
const res = findMajority(arr);
console.log(res.join(" "));
Similar Reads
Find all array elements occurring more than âN/3â times
Given an array arr[] consisting of n integers, the task is to find all the array elements which occurs more than floor(n/3) times.Note: The returned array of majority elements should be sorted. Examples: Input: arr[] = {2, 2, 3, 1, 3, 2, 1, 1}Output: {1, 2}Explanation: The frequency of 1 and 2 is 3,
15+ min read
Boyer-Moore Majority Voting Algorithm for Searching elements having more than K Occurrences
The Boyer-Moore Majority Voting Algorithm is a well-known and efficient algorithm used to find the majority element in an array, i.e., an element that appears more than n/2 times. This algorithm, initially designed by Robert S. Boyer and J Strother Moore in 1981, is widely used in various applicatio
9 min read
Print all array elements occurring at least M times
Given an array arr[] consisting of N integers and a positive integer M, the task is to find the number of array elements that occur at least M times. Examples: Input: arr[] = {2, 3, 2, 2, 3, 5, 6, 3}, M = 2Output: 2 3Explanation:In the given array arr[], the element that occurs at least M number of
15 min read
Count majority element in a matrix
Given a NxM matrix of integers containing duplicate elements. The task is to find the count of all majority occurring elements in the given matrix, where majority element are those whose frequency is greater than or equal to (N*M)/2. Examples: Input : mat[] = {{1, 1, 2}, {2, 3, 3}, {4, 3, 3}} Output
6 min read
Find elements larger than half of the elements in an array | Set 2
Given an array arr[] consisting of N positive integers, the task is to find the elements which are greater than at least half of the array elements. Examples: Input: arr[] = {1, 6, 3, 4}Output: 4 6Explanation:Size of the array is 4. The elements which are greater than atleast N/2(= 4/2 = 2) elements
7 min read
Find majority element using Bit Magic
Pre-requisite: Majority Element, Majority Element | Set-2 (Hashing)Given an array of size N, find the majority element. The majority element is the element that appears more than n/2 times in the given array. Examples: Input: {3, 3, 4, 2, 4, 4, 2, 4, 4} Output: 4 Input: {3, 3, 6, 2, 4, 4, 2, 4} Outp
8 min read
Count subarrays having exactly K elements occurring at least twice
Given an array arr[] consisting of N integers and a positive integer K, the task is to count the number of subarrays having exactly K elements occurring at least twice. Examples: Input: arr[] = {1, 1, 1, 2, 2}, K = 1Output: 7Explanation: The subarrays having exactly 1 element occurring at least twic
11 min read
Remove elements that appear strictly less than k times
Given an array of integers, remove all the elements which appear strictly less than k times. Examples: Input : arr[] = {1, 2, 2, 3, 2, 3, 4} k = 2 Output : 2 2 3 2 3 Explanation : {1, 4} appears less than 2 times. Approach : Take a hash map, which will store the frequency of all the elements in the
12 min read
Queries for count of elements not present in range
Given an integer N which represents the total number of IDs present, a 2D array arr of size Mx2, where arr[i] = [ID, score] and 1D array query of size Q. We can assign multiple scores to a single ID. For each query q[i] where 0 <= i < Q, find the number of IDs who don't have any scores within
10 min read
Find an index of maximum occurring element with equal probability
Given an array of integers, find the most occurring element of the array and return any one of its indexes randomly with equal probability.Examples: Input: arr[] = [-1, 4, 9, 7, 7, 2, 7, 3, 0, 9, 6, 5, 7, 8, 9] Output: Element with maximum frequency present at index 6 OR Element with maximum frequen
8 min read