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 Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Find frequency of each element in given 3D Array
Next article icon

Find the frequency of each element in a sorted array

Last Updated : 05 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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
              Frequency of 9 is: 2
              Frequency of 10 is: 1

Input: arr[] = {2, 2, 6, 6, 7, 7, 7, 11} 
Output:  Frequency of 2 is: 2
               Frequency of 6 is: 2
               Frequency of 7 is: 3
               Frequency of 11 is: 1

 

Naive Approach: The simplest approach is to traverse the array and keep the count of every element encountered in a HashMap and then, in the end, print the frequencies of every element by traversing the HashMap. This approach is already implemented here.

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

Efficient Approach: The above approach can be optimized in terms of space used based on the fact that, in a sorted array, the same elements occur consecutively, so the idea is to maintain a variable to keep track of the frequency of elements while traversing the array. Follow the steps below to solve the problem:

  • Initialize a variable, say freq as 1 to store the frequency of elements.
  • Iterate in the range [1, N-1] using the variable i and perform the following steps:
    • If the value of arr[i] is equal to arr[i-1], increment freq by 1.
    • Else print value the frequency of arr[i-1] obtained in freq and then update freq to 1.
  • Finally, after the above step, print the frequency of the last distinct element of the array as freq.

Below is the implementation of the above approach:

C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;      // Function to print the frequency     // of each element of the sorted array      void printFreq(vector<int> &arr, int N)     {                 // Stores the frequency of an element         int freq = 1;                // Traverse the array arr[]         for (int i = 1; i < N; i++)         {                        // If the current element is equal             // to the previous element             if (arr[i] == arr[i - 1])             {                                // Increment the freq by 1                 freq++;             }                    // Otherwise,             else {                 cout<<"Frequency of "<<arr[i - 1]<< " is: " << freq<<endl;                 // Update freq                 freq = 1;             }         }                 // Print the frequency of the last element        cout<<"Frequency of "<<arr[N - 1]<< " is: " << freq<<endl;        }      // Driver Code     int main()      {                // Given Input         vector<int> arr             = { 1, 1, 1, 2, 3, 3, 5, 5,                 8, 8, 8, 9, 9, 10 };         int N = arr.size();                // Function Call         printFreq(arr, N);     return 0;     }      // This code is contributed by codersaty 
Java
// Java program for the above approach import java.io.*; import java.lang.*; import java.util.*;  class GFG {      // Function to print the frequency     // of each element of the sorted array     static void printFreq(int arr[], int N)     {          // Stores the frequency of an element         int freq = 1;          // Traverse the array arr[]         for (int i = 1; i < N; i++) {             // If the current element is equal             // to the previous element             if (arr[i] == arr[i - 1]) {                 // Increment the freq by 1                 freq++;             }              // Otherwise,             else {                 System.out.println("Frequency of "                                    + arr[i - 1]                                    + " is: " + freq);                 // Update freq                 freq = 1;             }         }          // Print the frequency of the last element         System.out.println("Frequency of "                            + arr[N - 1]                            + " is: " + freq);     }      // Driver Code     public static void main(String args[])     {         // Given Input         int arr[]             = { 1, 1, 1, 2, 3, 3, 5, 5,                 8, 8, 8, 9, 9, 10 };         int N = arr.length;          // Function Call         printFreq(arr, N);     } } 
Python3
# Python3 program for the above approach  # Function to print the frequency # of each element of the sorted array def printFreq(arr, N):        # Stores the frequency of an element     freq = 1      # Traverse the array arr[]     for i in range(1, N, 1):                # If the current element is equal         # to the previous element         if (arr[i] == arr[i - 1]):                        # Increment the freq by 1             freq += 1          # Otherwise,         else:             print("Frequency of",arr[i - 1],"is:",freq)                 # Update freq             freq = 1      # Print the frequency of the last element     print("Frequency of",arr[N - 1],"is:",freq)  # Driver Code if __name__ == '__main__':        # Given Input     arr = [1, 1, 1, 2, 3, 3, 5, 5,8, 8, 8, 9, 9, 10]     N = len(arr)      # Function Call     printFreq(arr, N)          # This code is contributed by ipg2016107. 
C#
// C# program for the above approach using System;  public class GFG{      // Function to print the frequency // of each element of the sorted array static void printFreq(int[] arr, int N) {      // Stores the frequency of an element     int freq = 1;      // Traverse the array arr[]     for (int i = 1; i < N; i++)     {        // If the current element is equal       // to the previous element       if (arr[i] == arr[i - 1])       {          // Increment the freq by 1         freq++;       }        // Otherwise,       else {         Console.WriteLine("Frequency of " + arr[i - 1] + " is: " + freq);         // Update freq         freq = 1;       }     }      // Print the frequency of the last element     Console.WriteLine("Frequency of " + arr[N - 1] + " is: " + freq); }  // Driver Code static public void Main (){      // Given Input     int[] arr = { 1, 1, 1, 2, 3, 3, 5, 5,                   8, 8, 8, 9, 9, 10 };     int N = arr.Length;            // Function Call     printFreq(arr, N); } }  // This code is contributed by Dharanendra L V. 
JavaScript
<script>  // JavaScript program for the above approach  // Function to print the frequency // of each element of the sorted array function printFreq(arr, N)  {          // Stores the frequency of an element     let freq = 1;      // Traverse the array arr[]     for(let i = 1; i < N; i++)      {                  // If the current element is equal         // to the previous element         if (arr[i] == arr[i - 1])         {                          // Increment the freq by 1             freq++;         }          // Otherwise,         else         {             document.write("Frequency of " +                            parseInt(arr[i - 1]) + " is: " +                            parseInt(freq) + "<br>");                                         // Update freq             freq = 1;         }     }      // Print the frequency of the last element     document.write("Frequency of " +                     parseInt(arr[N - 1]) + " is: " +                     parseInt(freq) + "<br>"); }  // Driver Code  // Given Input let arr = [ 1, 1, 1, 2, 3, 3, 5, 5,             8, 8, 8, 9, 9, 10 ]; let N = arr.length;  // Function Call printFreq(arr, N);  // This code is contributed by Potta Lokesh  </script> 

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 Frequency of 9 is: 2 Frequency of 10 is: 1

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

Another approach :- using unordered_map

   Initialize a hashmap to store the frequency of each element.
   Traverse the array and insert each element into the hashmap. If an element already exists in the hashmap, increment its frequency.
   Print the frequency of each element in the hashmap.

Here's the implementation of the function frequency_sorted_array_3() using this approach:

C++
#include <iostream> #include <unordered_map> #include <vector>  using namespace std;  // Function to calculate the frequency of each element in a // sorted array using the hashmap approach void frequency_sorted_array_3(vector<int> arr) {     int n = arr.size();      // Create a hashmap to store the frequency of each     // element     unordered_map<int, int> freq;      // Traverse the array and insert each element into the     // hashmap     for (int i = 0; i < n; i++) {         freq[arr[i]]++;     }      // Print the frequency of each element in the hashmap     for (auto it : freq) {         cout << it.first << " occurs " << it.second              << " times" << endl;     } }  int main() {     vector<int> arr         = { 1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 };      frequency_sorted_array_3(arr);      return 0; } 
Java
import java.util.*;  public class Main {      // Function to calculate the frequency of     // each element in a sorted array using the hashmap     // approach     static void frequencySortedArray(List<Integer> arr)     {         int n = arr.size();          // Create a hashmap to store the frequency of each         // element         Map<Integer, Integer> freq = new LinkedHashMap<>();          // Traverse the array and insert each element into         // the hashmap         for (int i = 0; i < n; i++) {             freq.put(arr.get(i),                      freq.getOrDefault(arr.get(i), 0) + 1);         }          // Print the frequency of each element in the         // hashmap         for (Map.Entry<Integer, Integer> entry :              freq.entrySet()) {             System.out.println(entry.getKey() + " occurs "                                + entry.getValue()                                + " times");         }     }      public static void main(String[] args)     {         List<Integer> arr = Arrays.asList(             1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10);          frequencySortedArray(arr);     } } 
Python3
def frequency_sorted_array_3(arr):     n = len(arr)      # Create a dictionary to store the frequency of each element     freq = {}      # Traverse the array and insert each element into the dictionary     for i in range(n):         if arr[i] in freq:             freq[arr[i]] += 1         else:             freq[arr[i]] = 1      # Print the frequency of each element in the dictionary     for key in freq:         print(f"{key} occurs {freq[key]} times")   arr = [1, 1, 1, 2, 3, 3, 5, 5,        8, 8, 8, 9, 9, 10] frequency_sorted_array_3(arr) 
JavaScript
function frequency_sorted_array_3(arr) {     let n = arr.length;      // Create a hashmap to store the frequency of each element     let freq = {};      // Traverse the array and insert each element into the hashmap     for (let i = 0; i < n; i++) {         if (freq[arr[i]]) {             freq[arr[i]]++;         } else {             freq[arr[i]] = 1;         }     }      // Print the frequency of each element in the hashmap     for (let key in freq) {         console.log(key + " occurs " + freq[key] + " times");     } }  let arr = [1, 1, 1, 2, 3, 3, 5, 5,                 8, 8, 8, 9, 9, 10]; frequency_sorted_array_3(arr); 
C#
using System; using System.Collections.Generic;  public class Program {     // Function to calculate the frequency of     // each element in a sorted array using the hashmap     // approach     static void FrequencySortedArray(List<int> arr)     {         int n = arr.Count;          // Create a dictionary to store the frequency of         // each element         Dictionary<int, int> freq             = new Dictionary<int, int>();          // Traverse the array and insert each element into         // the dictionary         for (int i = 0; i < n; i++) {             if (freq.ContainsKey(arr[i]))                 freq[arr[i]]++;             else                 freq.Add(arr[i], 1);         }          // Print the frequency of each element in the         // dictionary         foreach(KeyValuePair<int, int> entry in freq)         {             Console.WriteLine(entry.Key + " occurs "                               + entry.Value + " times");         }     }      public static void Main(string[] args)     {         List<int> arr = new List<int>() {             1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10         };          FrequencySortedArray(arr);     } } 

Output
10 occurs 1 times 9 occurs 2 times 8 occurs 3 times 5 occurs 2 times 3 occurs 2 times 2 occurs 1 times 1 occurs 3 times

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


Next Article
Find frequency of each element in given 3D Array

A

aayushi agarwal
Improve
Article Tags :
  • Algorithms
  • Searching
  • Hash
  • DSA
  • Arrays
  • frequency-counting
Practice Tags :
  • Algorithms
  • Arrays
  • Hash
  • Searching

Similar Reads

  • Find the Frequency of Each Element in a Vector in C++
    The frequency of an element is number of times it occurred in the vector. In this article, we will learn different methods to find the frequency of each element in a vector in C++. The simplest method to find the frequency of each element in a vector is by iterating the vector and storing the count
    3 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 frequency of each element in a limited range array in less than O(n) time
    Given a sorted array arr[] of positive integers, the task is to find the frequency for each element in the array. Assume all elements in the array are less than some constant M Note: Do this without traversing the complete array. i.e. expected time complexity is less than O(n) Examples: Input: arr[]
    10 min read
  • Find the array element having maximum frequency of the digit K
    Given an array arr[] of size N and an integer K, the task is to find an array element that contains the digit K a maximum number of times. If more than one solutions exist, then print any one of them. Otherwise, print -1. Examples: Input: arr[] = {3, 77, 343, 456}, K = 3 Output: 343 Explanation: Fre
    15 min read
  • Cumulative frequency of count of each element in an unsorted array
    Given an unsorted array. The task is to calculate the cumulative frequency of each element of the array using a count array. Examples: Input : arr[] = [1, 2, 2, 1, 3, 4]Output :1->2 2->4 3->5 4->6Input : arr[] = [1, 1, 1, 2, 2, 2]Output :1->3 2->6 A simple solution is to use two ne
    9 min read
  • Find array elements with frequencies in range [l , r]
    Given an array of integers, find the elements from the array whose frequency lies in the range [l, r]. Examples: Input : arr[] = { 1, 2, 3, 3, 2, 2, 5 } l = 2, r = 3 Output : 2 3 3 2 2 Approach : Take a hash map, which will store the frequency of all the elements in the array.Now, traverse once agai
    9 min read
  • Find element with highest frequency in given nested Array
    Given an array arr[] of N integers. The task is to create a frequency array freq[] of the given array arr[] and find the maximum element of the frequency array. If two elements have the same frequency in the array freq[], then return the element which has a smaller value. Examples: Input: arr[] = {1
    8 min read
  • Find the Kth occurrence of an element in a sorted Array
    Given a sorted array arr[] of size N, an integer X, and a positive integer K, the task is to find the index of Kth occurrence of X in the given array. Examples: Input: N = 10, arr[] = [1, 2, 3, 3, 4, 5, 5, 5, 5, 5], X = 5, K = 2Output: Starting index of the array is '0' Second occurrence of 5 is at
    15+ min read
  • Frequency of an element 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 = 5Output : 3Input : a[] = {1, 2, 3} x = 4Output : 0 Unsorted ArrayThe idea is simple, we initialize count as 0. We traverse the array in a linear fashion. For every element tha
    9 min read
  • Find element in a sorted array whose frequency is greater than or equal to n/2.
    Given a sorted array of length n, find the number in array that appears more than or equal to n/2 times. It is given that such element always exists. Examples: Input : 2 3 3 4 Output : 3 Input : 3 4 5 5 5 Output : 5 Input : 1 1 1 2 3 Output : 1 To find that number, we traverse the array and check th
    3 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