Find array elements with frequencies in range [l , r]
Last Updated :
24 Mar, 2023
Given an array of integers, find the elements from the array whose frequency lies in the range [l, r].
Examples:
Input : arr[] = { 1, 2, 3, 3, 2, 2, 5 }
l = 2, r = 3
Output : 2 3 3 2 2
Approach :
- Take a hash map, which will store the frequency of all the elements in the array.
- Now, traverse once again.
- Print the elements whose frequency lies between the range [l, r].
C++
// C++ program to find the elements whose
// frequency lies in the range [l, r]
#include "iostream"
#include "unordered_map"
using namespace std;
void findElements(int arr[], int n, int l, int r)
{
// Hash map which will store the
// frequency of the elements of the array.
unordered_map<int, int> mp;
for (int i = 0; i < n; ++i) {
// Increment the frequency
// of the element by 1.
mp[arr[i]]++;
}
for (int i = 0; i < n; ++i) {
// Print the element whose frequency
// lies in the range [l, r]
if (l <= mp[arr[i]] && mp[arr[i] <= r]) {
cout << arr[i] << " ";
}
}
}
int main()
{
int arr[] = { 1, 2, 3, 3, 2, 2, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
int l = 2, r = 3;
findElements(arr, n, l, r);
return 0;
}
Java
import java.util.HashMap;
import java.util.Map;
// Java program to find the elements whose
// frequency lies in the range [l, r]
public class GFG {
static void findElements(int arr[], int n, int l, int r) {
// Hash map which will store the
// frequency of the elements of the array.
Map<Integer, Integer> mp = new HashMap<Integer, Integer>();
for (int i = 0; i < n; ++i) {
// Increment the frequency
// of the element by 1.
int a=0;
if(mp.get(arr[i])==null){
a=1;
}
else{
a = mp.get(arr[i])+1;
}
mp.put(arr[i], a);
}
for (int i = 0; i < n; ++i) {
// Print the element whose frequency
// lies in the range [l, r]
if (l <= mp.get(arr[i]) && (mp.get(arr[i]) <= r)) {
System.out.print(arr[i] + " ");
}
}
}
public static void main(String[] args) {
int arr[] = {1, 2, 3, 3, 2, 2, 5};
int n = arr.length;
int l = 2, r = 3;
findElements(arr, n, l, r);
}
}
/*This code is contributed by PrinciRaj1992*/
Python3
# Python 3 program to find the elements whose
# frequency lies in the range [l, r]
def findElements(arr, n, l, r):
# Hash map which will store the
# frequency of the elements of the array.
mp = {i:0 for i in range(len(arr))}
for i in range(n):
# Increment the frequency
# of the element by 1.
mp[arr[i]] += 1
for i in range(n):
# Print the element whose frequency
# lies in the range [l, r]
if (l <= mp[arr[i]] and mp[arr[i] <= r]):
print(arr[i], end = " ")
# Driver Code
if __name__ == '__main__':
arr = [1, 2, 3, 3, 2, 2, 5]
n = len(arr)
l = 2
r = 3
findElements(arr, n, l, r)
# This code is contributed by
# Shashank_Sharma
C#
// C# program to find the elements whose
// frequency lies in the range [l, r]
using System;
using System.Collections.Generic;
class GFG
{
static void findElements(int []arr, int n, int l, int r)
{
// Hash map which will store the
// frequency of the elements of the array.
Dictionary<int, int> mp = new Dictionary<int, int>();
for (int i = 0; i < n; ++i)
{
// Increment the frequency
// of the element by 1.
int a = 0;
if(!mp.ContainsKey(arr[i]))
{
a = 1;
}
else
{
a = mp[arr[i]]+1;
}
if(!mp.ContainsKey(arr[i]))
{
mp.Add(arr[i], a);
}
else
{
mp.Remove(arr[i]);
mp.Add(arr[i], a);
}
}
for (int i = 0; i < n; ++i)
{
// Print the element whose frequency
// lies in the range [l, r]
if (mp.ContainsKey(arr[i]) &&
l <= mp[arr[i]] &&
(mp[arr[i]] <= r))
{
Console.Write(arr[i] + " ");
}
}
}
// Driver code
public static void Main(String[] args)
{
int []arr = {1, 2, 3, 3, 2, 2, 5};
int n = arr.Length;
int l = 2, r = 3;
findElements(arr, n, l, r);
}
}
// This code has been contributed by 29AjayKumar
JavaScript
<script>
// Javascript program to find the elements whose
// frequency lies in the range [l, r]
function findElements(arr, n, l, r)
{
// Hash map which will store the
// frequency of the elements of the array.
let mp = new Map();
for(let i = 0; i < n; ++i)
{
// Increment the frequency
// of the element by 1.
let a = 0;
if (mp.get(arr[i]) == null)
{
a = 1;
}
else
{
a = mp.get(arr[i]) + 1;
}
mp.set(arr[i], a);
}
for(let i = 0; i < n; ++i)
{
// Print the element whose frequency
// lies in the range [l, r]
if (l <= mp.get(arr[i]) &&
(mp.get(arr[i]) <= r))
{
document.write(arr[i] + " ");
}
}
}
// Driver Code
let arr = [ 1, 2, 3, 3, 2, 2, 5 ];
let n = arr.length;
let l = 2, r = 3;
findElements(arr, n, l, r);
// This code is contributed by code_hunt
</script>
Time Complexity: O(N)
Auxiliary space: O(N)
Efficient Approach( Space optimization): we can use binary search . First sort the whole array for binary search function and then find frequency of all array element . Then check if the frequency of array element lies in the range [L,R]. If lies , then print that element .
Below is the implementation of the above approach:
C++
// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to print elements that frequency
// lies in the range [L,R]
void findElements(int *arr, int n , int l , int r)
{
sort(arr,arr+n);//sort array for binary search
for(int i = 0 ; i < n ;i++)
{
//index of first and last occ of arr[i] using binary
//search Upper and lower bound function
int first_index = lower_bound(arr,arr+n,arr[i])- arr;
int last_index = upper_bound(arr,arr+n,arr[i])- arr-1;
int fre = last_index-first_index+1;//finding frequency
if(fre >= l and fre <=r)
{ //printing element if its frequency lies in the range [L,R]
cout << arr[i] <<" ";
}
}
}
// Drive code
int main()
{
int arr[] = { 1, 2, 3, 3, 2, 2, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
int l = 2, r = 3;
// Function call
findElements( arr, n, l , r );
return 0;
}
// This Approach is contributed by nikhilsainiofficial546
Java
// Java implementation of the above approach
import java.util.*;
public class FrequencyRange {
// Function to print elements that frequency
// lies in the range [L,R]
static void findElements(int[] arr, int n, int l, int r)
{
Arrays.sort(arr);
// sort array for binary search
for (int i = 0; i < n; i++) {
// index of first and last occ of arr[i] using
// binary search Upper and lower bound function
int first_index
= Arrays.binarySearch(arr, arr[i]);
int last_index
= Arrays.binarySearch(arr, arr[i]);
while (first_index > 0
&& arr[first_index - 1] == arr[i]) {
first_index--;
}
while (last_index < n - 1
&& arr[last_index + 1] == arr[i]) {
last_index++;
}
int fre = last_index - first_index + 1;
// finding frequency
if (fre >= l && fre <= r) {
// printing element if its
// frequency lies in the
// range [L,R]
System.out.print(arr[i] + " ");
}
}
}
// Driver's code
public static void main(String[] args)
{
int[] arr = { 1, 2, 3, 3, 2, 2, 5 };
int n = arr.length;
int l = 2, r = 3;
// Function call
findElements(arr, n, l, r);
}
}
Python3
import bisect
# Function to print elements whose frequency
# lies in the range [L,R]
def findElements(arr, n, l, r):
arr.sort() # sort array for binary search
for i in range(n):
# index of first and last occ of arr[i] using binary
# search Upper and lower bound function
first_index = bisect.bisect_left(arr, arr[i])
last_index = bisect.bisect_right(arr, arr[i])
fre = last_index - first_index # finding frequency
if fre >= l and fre <= r: # printing element if its frequency lies in the range [L,R]
print(str(arr[i]), end = " ")
print()
# Driver code
arr = [1, 2, 3, 3, 2, 2, 5]
n = len(arr)
l = 2
r = 3
# Function call
findElements(arr, n, l , r)
C#
using System;
class Program {
static void findElements(int[] arr, int n, int l, int r) {
Array.Sort(arr); // sort array for binary search
for (int i = 0; i < n; i++) {
// index of first and last occ of arr[i] using binary
// search Upper and lower bound function
int first_index = Array.BinarySearch(arr, arr[i]);
while (first_index > 0 && arr[first_index - 1] == arr[i]) {
first_index--;
}
int last_index = Array.BinarySearch(arr, arr[i]);
while (last_index < n - 1 && arr[last_index + 1] == arr[i]) {
last_index++;
}
int fre = last_index - first_index + 1; // finding frequency
if (fre >= l && fre <= r) { // printing element if its frequency lies in the range [L,R]
Console.Write(arr[i] + " ");
}
}
}
static void Main() {
int[] arr = { 1, 2, 3, 3, 2, 2, 5 };
int n = arr.Length;
int l = 2, r = 3;
// Function call
findElements(arr, n, l, r);
}
}
JavaScript
// Function to print elements that frequency
// lies in the range [L,R]
function findElements(arr, n, l, r) {
arr.sort(); // sort array for binary search
for (let i = 0; i < n; i++) {
// index of first and last occ of arr[i] using binary
// search Upper and lower bound function
const first_index = arr.indexOf(arr[i]);
const last_index = arr.lastIndexOf(arr[i]);
const fre = last_index - first_index + 1; // finding frequency
if (fre >= l && fre <= r) { // printing element if its frequency lies in the range [L,R]
console.log(arr[i] + " ");
}
}
}
// Drive code
const arr = [1, 2, 3, 3, 2, 2, 5];
const n = arr.length;
const l = 2;
const r = 3;
// Function call
findElements(arr, n, l , r);
Time Complexity: O(N*Log2N)
Auxiliary space: O(1)
Similar Reads
Range Queries for Frequencies of array elements Given an array of n non-negative integers. The task is to find frequency of a particular element in the arbitrary range of array[]. The range is given as positions (not 0 based indexes) in array. There can be multiple queries of given type. Examples: Input : arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11}; lef
13 min read
Find element with highest frequency in given nested Array Given an array arr[] of N integers. The task is to create a frequency array freq[] of the given array arr[] and find the maximum element of the frequency array. If two elements have the same frequency in the array freq[], then return the element which has a smaller value. Examples: Input: arr[] = {1
8 min read
Find the frequency of each element in a sorted array Given a sorted array, arr[] consisting of N integers, the task is to find the frequencies of each array element. Examples: Input: arr[] = {1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10} Output: Frequency of 1 is: 3 Frequency of 2 is: 1 Frequency of 3 is: 2 Frequency of 5 is: 2 Frequency of 8 is: 3 Frequ
10 min read
Elements of first array that have more frequencies Given two arrays (which may or may not be sorted). These arrays are such that they might have some common elements in them. We need to find elements whose counts of occurrences are more in first array than second. Examples: Input : ar1[] = {1, 2, 2, 2, 3, 3, 4, 5} ar2[] = {2, 2, 3, 3, 3, 4} Output :
7 min read
Array range queries for elements with frequency same as value Given an array of N numbers, the task is to answer Q queries of the following type: query(start, end) = Number of times a number x occurs exactly x times in a subarray from start to end Examples: Input : arr = {1, 2, 2, 3, 3, 3} Query 1: start = 0, end = 1, Query 2: start = 1, end = 1, Query 3: star
15+ min read