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
Frequency of 9 is: 2
Frequency of 10 is: 1
Input: arr[] = {2, 2, 6, 6, 7, 7, 7, 11}
Output: Frequency of 2 is: 2
Frequency of 6 is: 2
Frequency of 7 is: 3
Frequency of 11 is: 1
Naive Approach: The simplest approach is to traverse the array and keep the count of every element encountered in a HashMap and then, in the end, print the frequencies of every element by traversing the HashMap. This approach is already implemented here.
Time Complexity: O(N)
Auxiliary Space: O(N)
Efficient Approach: The above approach can be optimized in terms of space used based on the fact that, in a sorted array, the same elements occur consecutively, so the idea is to maintain a variable to keep track of the frequency of elements while traversing the array. Follow the steps below to solve the problem:
- Initialize a variable, say freq as 1 to store the frequency of elements.
- Iterate in the range [1, N-1] using the variable i and perform the following steps:
- If the value of arr[i] is equal to arr[i-1], increment freq by 1.
- Else print value the frequency of arr[i-1] obtained in freq and then update freq to 1.
- Finally, after the above step, print the frequency of the last distinct element of the array as freq.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void printFreq(vector< int > &arr, int N)
{
int freq = 1;
for ( int i = 1; i < N; i++)
{
if (arr[i] == arr[i - 1])
{
freq++;
}
else {
cout<< "Frequency of " <<arr[i - 1]<< " is: " << freq<<endl;
freq = 1;
}
}
cout<< "Frequency of " <<arr[N - 1]<< " is: " << freq<<endl;
}
int main()
{
vector< int > arr
= { 1, 1, 1, 2, 3, 3, 5, 5,
8, 8, 8, 9, 9, 10 };
int N = arr.size();
printFreq(arr, N);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
static void printFreq( int arr[], int N)
{
int freq = 1 ;
for ( int i = 1 ; i < N; i++) {
if (arr[i] == arr[i - 1 ]) {
freq++;
}
else {
System.out.println( "Frequency of "
+ arr[i - 1 ]
+ " is: " + freq);
freq = 1 ;
}
}
System.out.println( "Frequency of "
+ arr[N - 1 ]
+ " is: " + freq);
}
public static void main(String args[])
{
int arr[]
= { 1 , 1 , 1 , 2 , 3 , 3 , 5 , 5 ,
8 , 8 , 8 , 9 , 9 , 10 };
int N = arr.length;
printFreq(arr, N);
}
}
|
Python3
def printFreq(arr, N):
freq = 1
for i in range ( 1 , N, 1 ):
if (arr[i] = = arr[i - 1 ]):
freq + = 1
else :
print ( "Frequency of" ,arr[i - 1 ], "is:" ,freq)
freq = 1
print ( "Frequency of" ,arr[N - 1 ], "is:" ,freq)
if __name__ = = '__main__' :
arr = [ 1 , 1 , 1 , 2 , 3 , 3 , 5 , 5 , 8 , 8 , 8 , 9 , 9 , 10 ]
N = len (arr)
printFreq(arr, N)
|
C#
using System;
public class GFG{
static void printFreq( int [] arr, int N)
{
int freq = 1;
for ( int i = 1; i < N; i++)
{
if (arr[i] == arr[i - 1])
{
freq++;
}
else {
Console.WriteLine( "Frequency of " + arr[i - 1] + " is: " + freq);
freq = 1;
}
}
Console.WriteLine( "Frequency of " + arr[N - 1] + " is: " + freq);
}
static public void Main (){
int [] arr = { 1, 1, 1, 2, 3, 3, 5, 5,
8, 8, 8, 9, 9, 10 };
int N = arr.Length;
printFreq(arr, N);
}
}
|
Javascript
<script>
function printFreq(arr, N)
{
let freq = 1;
for (let i = 1; i < N; i++)
{
if (arr[i] == arr[i - 1])
{
freq++;
}
else
{
document.write( "Frequency of " +
parseInt(arr[i - 1]) + " is: " +
parseInt(freq) + "<br>" );
freq = 1;
}
}
document.write( "Frequency of " +
parseInt(arr[N - 1]) + " is: " +
parseInt(freq) + "<br>" );
}
let arr = [ 1, 1, 1, 2, 3, 3, 5, 5,
8, 8, 8, 9, 9, 10 ];
let N = arr.length;
printFreq(arr, N);
</script>
|
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
Frequency of 9 is: 2
Frequency of 10 is: 1
Time Complexity: O(N)
Auxiliary Space: O(1)
Another approach :- using unordered_map
Initialize a hashmap to store the frequency of each element.
Traverse the array and insert each element into the hashmap. If an element already exists in the hashmap, increment its frequency.
Print the frequency of each element in the hashmap.
Here’s the implementation of the function frequency_sorted_array_3() using this approach:
C++
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
void frequency_sorted_array_3(vector< int > arr)
{
int n = arr.size();
unordered_map< int , int > freq;
for ( int i = 0; i < n; i++) {
freq[arr[i]]++;
}
for ( auto it : freq) {
cout << it.first << " occurs " << it.second
<< " times" << endl;
}
}
int main()
{
vector< int > arr
= { 1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 };
frequency_sorted_array_3(arr);
return 0;
}
|
Java
import java.util.*;
public class Main {
static void frequencySortedArray(List<Integer> arr)
{
int n = arr.size();
Map<Integer, Integer> freq = new LinkedHashMap<>();
for ( int i = 0 ; i < n; i++) {
freq.put(arr.get(i),
freq.getOrDefault(arr.get(i), 0 ) + 1 );
}
for (Map.Entry<Integer, Integer> entry :
freq.entrySet()) {
System.out.println(entry.getKey() + " occurs "
+ entry.getValue()
+ " times" );
}
}
public static void main(String[] args)
{
List<Integer> arr = Arrays.asList(
1 , 1 , 1 , 2 , 3 , 3 , 5 , 5 , 8 , 8 , 8 , 9 , 9 , 10 );
frequencySortedArray(arr);
}
}
|
Python3
def frequency_sorted_array_3(arr):
n = len (arr)
freq = {}
for i in range (n):
if arr[i] in freq:
freq[arr[i]] + = 1
else :
freq[arr[i]] = 1
for key in freq:
print (f "{key} occurs {freq[key]} times" )
arr = [ 1 , 1 , 1 , 2 , 3 , 3 , 5 , 5 ,
8 , 8 , 8 , 9 , 9 , 10 ]
frequency_sorted_array_3(arr)
|
Javascript
function frequency_sorted_array_3(arr) {
let n = arr.length;
let freq = {};
for (let i = 0; i < n; i++) {
if (freq[arr[i]]) {
freq[arr[i]]++;
} else {
freq[arr[i]] = 1;
}
}
for (let key in freq) {
console.log(key + " occurs " + freq[key] + " times" );
}
}
let arr = [1, 1, 1, 2, 3, 3, 5, 5,
8, 8, 8, 9, 9, 10];
frequency_sorted_array_3(arr);
|
C#
using System;
using System.Collections.Generic;
public class Program {
static void FrequencySortedArray(List< int > arr)
{
int n = arr.Count;
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.Add(arr[i], 1);
}
foreach (KeyValuePair< int , int > entry in freq)
{
Console.WriteLine(entry.Key + " occurs "
+ entry.Value + " times" );
}
}
public static void Main( string [] args)
{
List< int > arr = new List< int >() {
1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10
};
FrequencySortedArray(arr);
}
}
|
Output
10 occurs 1 times
9 occurs 2 times
8 occurs 3 times
5 occurs 2 times
3 occurs 2 times
2 occurs 1 times
1 occurs 3 times
Time Complexity: O(N)
Auxiliary Space: O(N)
Last Updated :
05 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...