Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Most frequent element in an array
Next article icon

Frequency of an element in an array

Last Updated : 17 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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

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. 

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>   

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:

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); 

Output
4

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

 


Next Article
Most frequent element in an array

S

Sangita Dey
Improve
Article Tags :
  • Misc
  • DSA
  • Arrays
  • Binary Search
Practice Tags :
  • Arrays
  • Binary Search
  • Misc

Similar Reads

  • Most frequent element in an array
    Given an array, the task is to find the most frequent element in it. If there are multiple elements that appear a maximum number of times, return the maximum element. Examples: Input : arr[] = [1, 3, 2, 1, 4, 1]Output : 1Explanation: 1 appears three times in array which is maximum frequency. Input :
    10 min read
  • Sum of all odd frequency elements in an array
    Given an array of integers containing duplicate elements. The task is to find the sum of all odd occurring elements in the given array. That is the sum of all such elements whose frequency is odd in the array. Examples: Input : arr[] = {1, 1, 2, 2, 3, 3, 3} Output : 9 The odd occurring element is 3,
    8 min read
  • Top K Frequent Elements in an Array
    Given an array arr[] and a positive integer k, the task is to find the k most frequently occurring elements from a given array. Note: If more than one element has same frequency then prioritise the larger element over the smaller one. Examples: Input: arr= [3, 1, 4, 4, 5, 2, 6, 1], k = 2Output: [4,
    15+ min read
  • Least frequent element in an array
    Given an array, find the least frequent element in it. If there are multiple elements that appear least number of times, print any one of them. Examples : Input : arr[] = {1, 3, 2, 1, 2, 2, 3, 1}Output : 3Explanation: 3 appears minimum number of times in given array. Input : arr[] = {10, 20, 30}Outp
    12 min read
  • Delete all odd frequency elements from an Array
    Given an array arr containing integers of size N, the task is to delete all the elements from the array that have odd frequencies.Examples: Input: arr[] = {3, 3, 3, 2, 2, 4, 7, 7} Output: {2, 2, 7, 7} Explanation: Frequency of 3 = 3 Frequency of 2 = 2 Frequency of 4 = 1 Frequency of 7 = 2 Therefore,
    5 min read
  • Mode of frequencies of given array elements
    Given an array arr[], the task is to find the mode of frequencies of elements of the given array. Examples: Input: arr[] = {6, 10, 3, 10, 8, 3, 6, 4}, N = 8Output: 2Explanation:Here (3, 10 and 6) have frequency 2, while (4 and 8) have frequency 1.Three numbers have frequency 2, while 2 numbers have
    6 min read
  • Find frequency of each element in given 3D Array
    Given a 3D array of size N*M*P consisting only of English alphabet characters, the task is to print the frequency of all the elements in increasing order. If the frequency is the same, print them in lexicographic ordering. Examples: Input: N = 3, M = 4, P = 5, matrix = { { {a, b, c, d, e}, {f, g, h,
    9 min read
  • Find the frequency of each element in a sorted array
    Given a sorted array, arr[] consisting of N integers, the task is to find the frequencies of each array element. Examples: Input: arr[] = {1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10} Output: Frequency of 1 is: 3 Frequency of 2 is: 1 Frequency of 3 is: 2 Frequency of 5 is: 2 Frequency of 8 is: 3 Frequ
    10 min read
  • Counting frequencies of array elements
    Given an array which may contain duplicates, print all elements and their frequencies. Examples: Input : arr[] = {10, 20, 20, 10, 10, 20, 5, 20}Output : 10 3 20 4 5 1Input : arr[] = {10, 20, 20}Output : 10 1 20 2 A simple solution is to run two loops. For every item count number of times, it occurs.
    15+ min read
  • Sum of all even occurring element in an array
    Given an array of integers containing duplicate elements. The task is to find the sum of all even occurring elements in the given array. That is the sum of all such elements whose frequency is even in the array. Examples: Input : arr[] = {1, 1, 2, 2, 3, 3, 3}Output : 6The even occurring element are
    12 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences