Skip to content

Frequency arrays

Course: Intro Class 2- DSA - chapter 4

Sometimes, we might want to maintain frequencies of something. Let’s take this problem:

Given a list of integers, find the integer with maximum frequency.

For example, if we are given an array with [1, 2, 1, 1, 3, 3], then the answer will be 1 as frequency of 1 is 3 vs that of 2 and 3 which are 1 and 2 respectively.

In these type of problems, what we can do is create a frequency array

A **frequency array, **is a special array that stores the frequencies of all the elements.

So in our example the frequency array can be something like this:

freq = 0, 3, 1, 2]

Where,

freq[0] = how many times 0 occurs in the array = 0

freq[1] = how many times 1 occurs in the array = 3

freq[2] = how many times 2 occurs in the array = 1

freq[3] = how many times 3 occurs in the array = 2

We can clearly see, the array elements of the main array are indices in the frequency array.

So what should be the size of the frequency array?

Now, how to calculate this frequency array

Solution

Maintain a frequency array freq[]. The size of this array should be the maximum value in nums list + 1 (Why?)

Iterate through all the elements and increase their frequency using: freq[nums[i]] += 1

Now loop through the frequency array and find which index has maximum frequency. The index is the answer.

Code
int max_value = *(max_element(arr, arr+n));
int freq[max_value + 1] = {0};
for(int i=0; i<n; i++) {
freq[arr[i]] += 1
}

💡 Remember, the size of the array is dependent on the array elements so in case the array elements are very large (~10^8) then don’t use this technique directly otherwise it will give Memory Limit Exceeded errors.

💡 Frequency array is a special form of hash table. So we can also use it with hashing for other data types or large integer values. Hashing is a technique of mapping one thing to another using a hash function. A hash function takes an argument of one type, and converts it into another value either of same type or different type. Generally, the output of hash functions is integers.