 GeeksforGeeks App
Open App Browser
Continue

# Find the frequency of a number in an array

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```

If array is not sorted

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.

## C++

 `// CPP program to count occurrences of an``// element in an unsorted array``#include``using` `namespace` `std;` `int` `frequency(``int` `a[], ``int` `n, ``int` `x)``{``    ``int` `count = 0;``    ``for` `(``int` `i=0; i < n; i++)``       ``if` `(a[i] == x)``          ``count++;``    ``return` `count;``}` `// Driver program``int` `main() {``    ``int` `a[] = {0, 5, 5, 5, 4};``    ``int` `x = 5;``    ``int` `n = ``sizeof``(a)/``sizeof``(a);``    ``cout << frequency(a, n, x);``    ``return` `0;``}`

## Java

 `// Java program to count``// occurrences of an``// element in an unsorted``// array` `import` `java.io.*;` `class` `GFG {``    ` `    ``static` `int` `frequency(``int` `a[],``    ``int` `n, ``int` `x)``    ``{``        ``int` `count = ``0``;``        ``for` `(``int` `i=``0``; i < n; i++)``        ``if` `(a[i] == x)``            ``count++;``        ``return` `count;``    ``}``    ` `    ``// Driver program``    ``public` `static` `void` `main (String[]``    ``args) {``        ` `        ``int` `a[] = {``0``, ``5``, ``5``, ``5``, ``4``};``        ``int` `x = ``5``;``        ``int` `n = a.length;``        ` `        ``System.out.println(frequency(a, n, x));``    ``}``}` `// This code is contributed``// by Ansu Kumari`

## Python3

 `# Python program to count``# occurrences of an``# element in an unsorted``# array``def` `frequency(a, x):``    ``count ``=` `0``    ` `    ``for` `i ``in` `a:``        ``if` `i ``=``=` `x: count ``+``=` `1``    ``return` `count` `# Driver program``a ``=` `[``0``, ``5``, ``5``, ``5``, ``4``]``x ``=` `5``print``(frequency(a, x))` `# This code is contributed by Ansu Kumari`

## C#

 `// C# program to count``// occurrences of an``// element in an unsorted``// array``using` `System;` `class` `GFG {``    ` `    ``static` `int` `frequency(``int` `[]a,``    ``int` `n, ``int` `x)``    ``{``        ``int` `count = 0;``        ``for` `(``int` `i=0; i < n; i++)``        ``if` `(a[i] == x)``            ``count++;``        ``return` `count;``    ``}``    ` `    ``// Driver program``    ``static` `public` `void` `Main (){``    ` `        ` `        ``int` `[]a = {0, 5, 5, 5, 4};``        ``int` `x = 5;``        ``int` `n = a.Length;``        ` `        ``Console.Write(frequency(a, n, x));``    ``}``}` `// This code is contributed``// by Anuj_67`

## PHP

 ``

## Javascript

 ``

Output

`3`

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

If the array is sorted

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.

Implementation:

## CPP

 `// CPP program to answer queries for frequencies``// in O(1) time.``#include ``using` `namespace` `std;`` ` `unordered_map<``int``, ``int``> hm;` `void` `countFreq(``int` `a[], ``int` `n)``{``    ``// Insert elements and their``    ``// frequencies in hash map.``    ``for` `(``int` `i=0; i

## Java

 `// Java program to answer``// queries for frequencies``// in O(1) time.` `import` `java.io.*;``import` `java.util.*;` `class` `GFG {``    ` `   ``static` `HashMap hm = ``new` `HashMap();` `   ``static` `void` `countFreq(``int` `a[], ``int` `n)``   ``{``        ``// Insert elements and their``        ``// frequencies in hash map.``        ``for` `(``int` `i=``0``; i

## Python3

 `# Python program to``# answer queries for``# frequencies``# in O(1) time.` `hm ``=` `{}` `def` `countFreq(a):``    ``global` `hm``    ` `    ``# Insert elements and their``    ``# frequencies in hash map.``    ` `    ``for` `i ``in` `a:``        ``if` `i ``in` `hm: hm[i] ``+``=` `1``        ``else``: hm[i] ``=` `1` `# Return frequency``# of x (Assumes that``# countFreq() is``# called before)``def` `query(x):``    ``if` `x ``in` `hm:``        ``return` `hm[x]``    ``return` `0` `# Driver program``a ``=` `[``1``, ``3``, ``2``, ``4``, ``2``, ``1``]``countFreq(a)``print``(query(``2``))``print``(query(``3``))``print``(query(``5``))` `# This code is contributed``# by Ansu Kumari`

## C#

 `// C# program to answer``// queries for frequencies``// in O(1) time.``using` `System;``using` `System.Collections.Generic;``class` `GFG``{``    ` `static` `Dictionary <``int``, ``int``> hm = ``new` `Dictionary<``int``, ``int``>();` `static` `void` `countFreq(``int` `[]a, ``int` `n)``{``    ``// Insert elements and their``    ``// frequencies in hash map.``    ``for` `(``int` `i = 0; i < n; i++)``        ``if` `(hm.ContainsKey(a[i]) )``            ``hm[a[i]] = hm[a[i]] + 1;``        ``else` `hm.Add(a[i], 1);``}``    ` `// Return frequency of x (Assumes that``// countFreq() is called before)``static` `int` `query(``int` `x)``{``    ``if` `(hm.ContainsKey(x))``        ``return` `hm[x];``    ``return` `0;``}``    ` `// Driver code``public` `static` `void` `Main(String[] args)``{``    ``int` `[]a = {1, 3, 2, 4, 2, 1};``    ``int` `n = a.Length;``    ``countFreq(a, n);``    ``Console.WriteLine(query(2));``    ``Console.WriteLine(query(3));``    ``Console.WriteLine(query(5));``}``}` `// This code is contributed by 29AjayKumar`

## Javascript

 ``

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.

Approach 2 :

In this approach I am using C++ STL 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:

## C++

 `#include ``using` `namespace` `std;``#include ``#include ``int` `main()``{``    ``int` `digit;``    ``digit = 7; ``// Specify the digit as a input to find the``               ``// occurrence of digit``    ``vector<``int``> v{ 7, 2, 3, 1, 7, 6, 7, 1, 3, 7 };``    ``auto` `itr``        ``= partition(v.begin(), v.end(),``                    ``[&digit](``int` `x) { ``return` `x == digit; });``    ``int` `count = distance(v.begin(), itr);``    ``cout << count << endl;``    ``return` `0;``}`

## Java

 `import` `java.util.*;``import` `java.util.stream.*;` `class` `Main {``    ``public` `static` `void` `main(String[] args) {``        ``int` `digit;``        ``digit = ``7``; ``// Specify the digit as a input to find the``                   ``// occurrence of digit``        ``List v = Arrays.asList(``7``, ``2``, ``3``, ``1``, ``7``, ``6``, ``7``, ``1``, ``3``, ``7``);``        ``List partitioned = v.stream().filter(x -> x == digit).collect(Collectors.toList());``        ``int` `count = partitioned.size();``        ``System.out.println(count);``    ``}``}`

## C#

 `using` `System;``using` `System.Collections.Generic;``using` `System.Linq;` `public` `class` `GFG``{``    ``static` `public` `void` `Main()``    ``{``        ``int` `digit;``        ``digit = 7; ``// Specify the digit as a input to find the``                   ``// occurrence of digit``        ``List<``int``> v = ``new` `List<``int``> { 7, 2, 3, 1, 7, 6, 7, 1, 3, 7 };``        ``var` `partitioned = v.Where(x => x == digit).ToList();``        ``int` `count = partitioned.Count();``        ``Console.WriteLine(count);``    ``}``}`

## Python

 `# Specify the digit as an input to find the occurrence of digit``digit ``=` `7``v ``=` `[``7``, ``2``, ``3``, ``1``, ``7``, ``6``, ``7``, ``1``, ``3``, ``7``]` `# Use the filter function to find all occurrences of the digit in the list``itr ``=` `filter``(``lambda` `x: x ``=``=` `digit, v)` `# Count the number of occurrences``count ``=` `len``(``list``(itr))` `print``(count)`

## Javascript

 `let digit;``digit = 7; ``// Specify the digit as a input to find the``           ``// occurrence of digit``let v = [7, 2, 3, 1, 7, 6, 7, 1, 3, 7];``let itr = v.filter(x => x === digit);``let count = itr.length;``console.log(count);`

Output

`4`

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

This article is contributed by Sangita Dey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

My Personal Notes arrow_drop_up