Open In App

Frequency of each element of an array of small ranged values

Last Updated : 09 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array where elements in small range. The maximum element in the array does not go beyond size of array. Find frequencies of elements.

Examples: 

Input : arr[] = {3, 1, 2, 3, 4, 5, 4}
Output: 1-->1
        2-->1
        3-->2
        4-->2
        5-->1

Input : arr[] = {1, 2, 2, 1, 2}
Output: 1-->2
        2-->3

Input : arr[] = {1, 2, 4}
Output: 1-->1
        2-->1
        4-->1

A simple solution is to use two nested loops. For each element (from 1 to n where n is size of array), count how many times it appears. Time complexity of this solution is O(n*n)

A better solution is to use sorting. First sort the array, after sorting, linearly traverse the array and count occurrences of each element. Time complexity of this solution is O(n Log n)

An efficient solution is to use hashing. We insert every element in a hash table and increment frequency. Time complexity of this solution is O(n). Please see Frequency Measuring Techniques for Competitive Programming for implementation.

An efficient solution for limited range 
The hashing based solution is fast, but requires hash function computations, etc. If we know that range is small, we use direct address table where we create an array of size equal to maximum value and use array elements as index.

Following is the implementation for above explanation: 

C++




// CPP program to find frequencies of elements in
// limited range array.
#include <bits/stdc++.h>
using namespace std;
 
void frequencyOfEach(int* arr, int n)
{
    // finding maximum element in array
    int max = *max_element(arr, arr + n);
 
    // make hash array of size equal to maximum
    // element in array
    int hash[max + 1] = { 0 };
 
    /* Counting frequency of each element of array
       and storing it in hash*/
    for (int i = 0; i < n; i++) {
        hash[arr[i]]++;
    }
 
    // printing frequency of elements
    for (int i = 0; i <= max; i++) {
 
        /* If hash[i] has stored any value
           i.e element has occurred atleast
           once in array */
        if (hash[i] != 0)
            cout << i << "-->" << hash[i] << "\n";
    }
}
 
int main()
{
    int arr[] = { 5, 2, 2, 3, 5, 1, 1, 5, 3, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    frequencyOfEach(arr, n);
    return 0;
}


Java




// Java program to find frequencies of elements in
// limited range array.
import java.util.*;
 
class solution
{
 
static void frequencyOfEach(int []arr, int n)
{
    int max = Integer.MIN_VALUE;
    // finding maximum element in array
    for (int i = 0;i<n;i++)
{
    if (arr[i]>max)
        max = arr[i];
}
     
 
    // make hash array of size equal to maximum
    // element in array
    int []hash = new int[max + 1];
    Arrays.fill(hash,0);
 
    /* Counting frequency of each element of array
    and storing it in hash*/
    for (int i = 0; i < n; i++) {
        hash[arr[i]]++;
    }
 
    // printing frequency of elements
    for (int i = 0; i <= max; i++) {
 
        /* If hash[i] has stored any value
        i.e element has occurred atleast
        once in array */
        if (hash[i] != 0)
            System.out.println(i+"-->"+hash[i]);
    }
}
 
public static void main(String args[])
{
    int []arr = { 5, 2, 2, 3, 5, 1, 1, 5, 3, 4 };
    int n = arr.length;
    frequencyOfEach(arr, n);
     
}
}
//This code is contributed by Surendra_Gangwar


Python3




# Python 3 program to find frequencies
# of elements in limited range array.
def frequencyOfEach(arr, n) :
     
    # finding maximum element in array
    max_element = max(arr)
 
    # make hash array of size equal
    # to maximum element in array
    hash = [0] * (max_element + 1)
 
    # Counting frequency of each element
    # of array and storing it in hash
    for i in range(n) :
        hash[arr[i]] += 1
     
    # printing frequency of elements
    for i in range(max_element + 1) :
 
        # If hash[i] has stored any value
        # i.e element has occurred atleast
        # once in array
        if (hash[i] != 0) :
            print(i, "-->", hash[i])
     
# Driver Code
if __name__ == "__main__" :
 
    arr = [ 5, 2, 2, 3, 5,
            1, 1, 5, 3, 4 ]
    n = len(arr)
    frequencyOfEach(arr, n);
 
# This code is contributed by Ryuga


C#




// C# program to find frequencies of elements in
// limited range array.
using System;
  
public class solution{
 
    static void frequencyOfEach(int []arr, int n)
    {
        int max = int.MinValue;
        // finding maximum element in array
        for (int i = 0;i<n;i++)
    {
        if (arr[i]>max)
            max = arr[i];
    }
 
 
        // make hash array of size equal to maximum
        // element in array
        int []hash = new int[max + 1];
 
        /* Counting frequency of each element of array
        and storing it in hash*/
        for (int i = 0; i < n; i++) {
            hash[arr[i]]++;
        }
 
        // printing frequency of elements
        for (int i = 0; i <= max; i++) {
 
            /* If hash[i] has stored any value
            i.e element has occurred atleast
            once in array */
            if (hash[i] != 0)
                Console.WriteLine (i+"-->"+hash[i]);
        }
    }
 
    public static void Main()
    {
        int []arr = { 5, 2, 2, 3, 5, 1, 1, 5, 3, 4 };
        int n = arr.Length;
        frequencyOfEach(arr, n);
 
    }
}
// This code is contributed by PrinciRaj1992


PHP




<?php
// PHP program to find frequencies of
// elements in limited range array.
 
function frequencyOfEach(&$arr, $n)
{
    // finding maximum element in array
    $max = max($arr);
 
    // make hash array of size equal to
    // maximum element in array
    $hash = array_fill(0, $max + 1, NULL);
 
    /* Counting frequency of each element
    of array and storing it in hash*/
    for ($i = 0; $i < $n; $i++)
    {
        $hash[$arr[$i]]++;
    }
 
    // printing frequency of elements
    for ($i = 0; $i <= $max; $i++)
    {
 
        /* If hash[i] has stored any value
        i.e element has occurred atleast
        once in array */
        if ($hash[$i] != 0)
            echo $i . "-->" . $hash[$i] . "\n";
    }
}
 
// Driver Code
$arr = array(5, 2, 2, 3, 5, 1, 1, 5, 3, 4 );
$n = sizeof($arr);
frequencyOfEach($arr, $n);
 
// This code is contributed by ita_c
?>


Javascript




<script>
// Javascript program to find frequencies of elements in
// limited range array.
     
function frequencyOfEach(arr,n)
{
let max = Number.MIN_VALUE;
 
    // finding maximum element in array
    for (let i = 0; i < n; i++)
    {
        if (arr[i] > max)
            max = arr[i];
    }
       
   
    // make hash array of size equal to maximum
    // element in array
    let hash = new Array(max + 1);
    for(let i = 0; i < hash.length; i++)
    {
        hash[i] = 0;
    }
     
   
    /* Counting frequency of each element of array
    and storing it in hash*/
    for (let i = 0; i < n; i++)
    {
        hash[arr[i]]++;
    }
   
    // printing frequency of elements
    for (let i = 0; i <= max; i++) {
   
        /* If hash[i] has stored any value
        i.e element has occurred atleast
        once in array */
        if (hash[i] != 0)
            document.write(i+"-->"+hash[i]+"<br>");
    }
}
 
let arr=[5, 2, 2, 3, 5, 1, 1, 5, 3, 4];
let n = arr.length;
frequencyOfEach(arr, n);
     
// This code is contributed by rag2127
</script>


Output

1-->2
2-->2
3-->2
4-->1
5-->3

Complexity Analysis:

  • Time Complexity: O(max_value) 
  • Auxiliary Space: O(max_value)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads