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.
C++
// CPP program to count occurrences of an
// element in an unsorted array
#include<iostream>
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[0]);
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
Python
# 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
JavaScript
<script>
// C# program to count occurrences of an element in an unsorted array
function frequency(a, n, x)
{
let count = 0;
for (let i=0; i < n; i++)
if (a[i] == x)
count++;
return count;
}
let a = [0, 5, 5, 5, 4];
let x = 5;
let n = a.length;
document.write(frequency(a, n, x));
</script>
PHP
<?php
// PHP program to count occurrences of an
// element in an unsorted array
function frequency($a, $n, $x)
{
$count = 0;
for ($i = 0; $i < $n; $i++)
if ($a[$i] == $x)
$count++;
return $count;
}
// Driver Code
$a = array (0, 5, 5, 5, 4);
$x = 5;
$n = sizeof($a);
echo frequency($a, $n, $x);
// This code is contributed by ajit
?>
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.
CPP
// CPP program to answer queries for frequencies
// in O(1) time.
#include <bits/stdc++.h>
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<n; i++)
hm[a[i]]++;
}
// Return frequency of x (Assumes that
// countFreq() is called before)
int query(int x)
{
return hm[x];
}
// Driver program
int main()
{
int a[] = {1, 3, 2, 4, 2, 1};
int n = sizeof(a)/sizeof(a[0]);
countFreq(a, n);
cout << query(2) << endl;
cout << query(3) << endl;
cout << query(5) << endl;
return 0;
}
Java
// Java program to answer
// queries for frequencies
// in O(1) time.
import java.io.*;
import java.util.*;
class GFG {
static HashMap <Integer, Integer> hm = new HashMap<Integer, Integer>();
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.put(a[i], hm.get(a[i]) + 1);
else hm.put(a[i] , 1);
}
// Return frequency of x (Assumes that
// countFreq() is called before)
static int query(int x)
{
if (hm.containsKey(x))
return hm.get(x);
return 0;
}
// Driver program
public static void main (String[] args) {
int a[] = {1, 3, 2, 4, 2, 1};
int n = a.length;
countFreq(a, n);
System.out.println(query(2));
System.out.println(query(3));
System.out.println(query(5));
}
}
// This code is contributed by Ansu Kumari
Python
# 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
<script>
// JavaScript program to answer
// queries for frequencies
// in O(1) time.
var hm = new Map();
function countFreq(a, n)
{
// Insert elements and their
// frequencies in hash map.
for (var i=0; i<n; i++)
{
if(hm.has(a[i]))
{
hm.set(a[i], hm.get(a[i])+1);
}
else
{
hm.set(a[i], 1);
}
}
}
// Return frequency of x (Assumes that
// countFreq() is called before)
function query(x)
{
if(hm.has(x))
{
return hm.get(x);
}
return 0;
}
// Driver program
var a = [1, 3, 2, 4, 2, 1];
var n = a.length;
countFreq(a, n);
document.write( query(2) + "<br>");
document.write( query(3) + "<br>");
document.write( query(5) + "<br>");
</script>
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:
C++
#include <iostream>
using namespace std;
#include <algorithm>
#include <vector>
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<Integer> v = Arrays.asList(7, 2, 3, 1, 7, 6, 7, 1, 3, 7);
List<Integer> partitioned = v.stream().filter(x -> x == digit).collect(Collectors.toList());
int count = partitioned.size();
System.out.println(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)
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);
}
}
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);
Time Complexity: O(N)
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem