VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-frequency-number-array/

⇱ Frequency of an element in an array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Frequency of an element in an array

Last Updated : 17 Jan, 2025

Given an array, a[], and an element x, find a number of occurrences of x in a[].

Examples: 

Input : a[] = {0, 5, 5, 5, 4}
x = 5
Output : 3

Input : a[] = {1, 2, 3}
x = 4
Output : 0

Unsorted Array

The idea is simple, we initialize count as 0. We traverse the array in a linear fashion. For every element that matches with x, we increment count. Finally, we return count. 

Below is the implementation of the approach.


Output
3

Time Complexity: O(n) 
Auxiliary Space: O(1)

Sorted Array

We can apply methods for both sorted and unsorted. But for a sorted array, we can optimize it to work in O(Log n) time using Binary Search. Please refer to below article for details.Count number of occurrences (or frequency) in a sorted array.

If there are multiple queries on a single array

We can use hashing to store frequencies of all elements. Then we can answer all queries in O(1) time. Please refer Frequency of each element in an unsorted array for details. 


Output
2
1
0

Time complexity: O(n) where n is the number of elements in the given array.
Auxiliary space: O(n) because using extra space for unordered_map.

Using Library Method

In this approach I am using Language functions only with below conditions.

Conditions :

  • To find the counts of digit we can't use count_if()  and count() functions.
  • Use STL and lambda functions only.

Examples :

Input : v = {7,2,3,1,7,6,7,1,3,7} digit = 7

Output : 4

Input : v = {7,2,3,1,7,6,7,1,3,7} digit = 10

Output : 0

Explanation :

To find the occurrence of a digit with these conditions follow the below steps,

1. Use partition(start, end, condition) function to get all the digits and return the pointer of the last digit.

2.  Use the distance(start , end) to get the distance from vector starting point to the last digit pointer which partition() function returns.

So, distance() function returns the occurrence of the digit and we can print it.

Below is the implementation of the above approach:


Output
4

Time Complexity: O(N)
Auxiliary Space: O(1)

Comment
Article Tags: