What data structure suits for finding frequency of each element in integer array? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What data structure suits for finding frequency of each element in integer array?

Array programming

28th Aug 2020, 6:54 AM
alagammai uma
alagammai uma - avatar
5 Answers
+ 3
alagammai uma Approach: Create an extra space of size n, as elements of the array is in the range 1 to n. Use the extra space as HashMap. Traverse the array and update the count of the current element. Finally, print the frequencies of the HashMap along with the indices. Algorithm: Create an extra space of size n (hm), use it as a HashMap. Traverse the array from start to end. For every element update hm[array[i]-1], i.e. hm[array[i]-1]++ Run a loop from 0 to n and print hm[array[i]-1] along with the index i
28th Aug 2020, 7:08 AM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 4
Approach ---------------------------- In this program, we need to count the occurrence of each unique element present in the array. One of the approach to resolve this problem is to maintain one array to store the counts of each element of the array. Loop through the array and count the occurrence of each element and store it in another array fr. In the above array, 1 has appeared 1 time, so, the frequency of 1 is 1. Similarly, 2 has appeared 4 times. The frequency of 2 is 4 and so on.
28th Aug 2020, 7:00 AM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 3
alagammai uma yes you can use .
28th Aug 2020, 7:03 AM
A S Raghuvanshi
A S Raghuvanshi - avatar
0
Can we use HashMap ?if so how?
28th Aug 2020, 7:01 AM
alagammai uma
alagammai uma - avatar
0
I will add the integers to the HashMap but how could I add their count?
28th Aug 2020, 7:04 AM
alagammai uma
alagammai uma - avatar