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
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
C++ Program to Find the Frequency of Elements in an Array
Next article icon

Frequency of an integer in the given array using Divide and Conquer

Last Updated : 03 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an unsorted array arr[] and an integer K, the task is to count the occurrences of K in the given array using the Divide and Conquer method.

Examples: 

Input: arr[] = {1, 1, 2, 2, 2, 2, 3}, K = 1 
Output: 2

Input: arr[] = {1, 1, 2, 2, 2, 2, 3}, K = 4 
Output: 0

Approach: The idea is to divide the array into two parts of equal size and count the number of occurrences of K in each half and then add them up.

  • Divide the array into two parts until there is only one element left in the array.
  • Check whether a single element in the array is K or not. If it is K then return 1 otherwise 0.
  • Add up the returned values for each of the elements to find the occurrence of K in the whole array.

Below is the implementation of the above approach: 

C++




// C++ implrmrntation of the approach
 
#include <iostream>
using namespace std;
 
// Function to return the frequency of x
// in the subarray arr[low...high]
int count(int arr[], int low, int high, int x)
{
 
    // If the subarray is invalid or the
    // element is not found
    if ((low > high)
        || (low == high && arr[low] != x))
        return 0;
 
    // If there's only a single element
    // which is equal to x
    if (low == high && arr[low] == x)
        return 1;
 
    // Divide the array into two parts and
    // then find the count of occurrences
    // of x in both the parts
    return count(arr, low,
                 (low + high) / 2, x)
           + count(arr, 1 + (low + high) / 2,
                   high, x);
}
 
// Driver code
int main()
{
    int arr[] = { 30, 1, 42, 5, 56, 3, 56, 9 };
    int n = sizeof(arr) / sizeof(int);
    int x = 56;
 
    cout << count(arr, 0, n - 1, x);
 
    return 0;
}
 
 

Java




// Java implrmrntation of the approach
 
class GFG {
 
    // Function to return the frequency of x
    // in the subarray arr[low...high]
    static int count(int arr[], int low,
                     int high, int x)
    {
 
        // If the subarray is invalid or the
        // element is not found
        if ((low > high)
            || (low == high && arr[low] != x))
            return 0;
 
        // If there's only a single element
        // which is equal to x
        if (low == high && arr[low] == x)
            return 1;
 
        // Divide the array into two parts and
        // then find the count of occurrences
        // of x in both the parts
        return count(arr, low,
                     (low + high) / 2, x)
            + count(arr, 1 + (low + high) / 2,
                    high, x);
    }
 
    // Driver code
    public static void main(String args[])
    {
        int arr[] = { 30, 1, 42, 5, 56, 3, 56, 9 };
        int n = arr.length;
        int x = 56;
        System.out.print(count(arr, 0, n - 1, x));
    }
}
 
 

Python3




# Python3 implrmrntation of the approach
 
# Function to return the frequency of x
# in the subarray arr[low...high]
def count(arr, low, high, x):
 
    # If the subarray is invalid or the
    # element is not found
    if ((low > high) or (low == high and arr[low] != x)):
        return 0;
 
    # If there's only a single element
    # which is equal to x
    if (low == high and arr[low] == x):
        return 1;
 
    # Divide the array into two parts and
    # then find the count of occurrences
    # of x in both the parts
    return count(arr, low, (low + high) // 2, x) +\
    count(arr, 1 + (low + high) // 2, high, x);
 
# Driver code
if __name__ == '__main__':
    arr = [ 30, 1, 42, 5, 56, 3, 56, 9];
    n = len(arr);
    x = 56;
    print(count(arr, 0, n - 1, x));
 
# This code is contributed by PrinciRaj1992
 
 

C#




// C# implrmrntation of the approach
using System;
 
class GFG
{
 
    // Function to return the frequency of x
    // in the subarray arr[low...high]
    static int count(int []arr, int low,
                    int high, int x)
    {
 
        // If the subarray is invalid or the
        // element is not found
        if ((low > high)
            || (low == high && arr[low] != x))
            return 0;
 
        // If there's only a single element
        // which is equal to x
        if (low == high && arr[low] == x)
            return 1;
 
        // Divide the array into two parts and
        // then find the count of occurrences
        // of x in both the parts
        return count(arr, low,
                    (low + high) / 2, x)
            + count(arr, 1 + (low + high) / 2,
                    high, x);
    }
 
    // Driver code
    public static void Main()
    {
        int []arr = { 30, 1, 42, 5, 56, 3, 56, 9 };
        int n = arr.Length;
        int x = 56;
        Console.Write(count(arr, 0, n - 1, x));
    }
}
 
// This code is contributed by AnkitRai01
 
 

Javascript




<script>
// Javascript implrmrntation of the approach
// Function to return the frequency of x
// in the subarray arr[low...high]
 
function count(arr, low, high, x) {
 
    // If the subarray is invalid or the
    // element is not found
    if ((low > high)
        || (low == high && arr[low] != x))
        return 0;
 
    // If there's only a single element
    // which is equal to x
    if (low == high && arr[low] == x)
        return 1;
 
    // Divide the array into two parts and
    // then find the count of occurrences
    // of x in both the parts
    return count(arr, low,
        Math.floor((low + high) / 2), x)
        + count(arr, 1 + Math.floor((low + high) / 2),
            high, x);
}
 
// Driver code
 
let arr = [30, 1, 42, 5, 56, 3, 56, 9];
let n = arr.length;
let x = 56;
 
document.write(count(arr, 0, n - 1, x));
 
// This code is contributed by _saurabh_jaiswal
</script>
 
 
Output: 
2

 

Time Complexity: O(NlogN)
 



Next Article
C++ Program to Find the Frequency of Elements in an Array

M

mohan_mohadikar
Improve
Article Tags :
  • Arrays
  • C Language
  • C Programs
  • C++
  • C++ Programs
  • Divide and Conquer
  • DSA
  • Java
  • Python
  • Recursion
Practice Tags :
  • CPP
  • Arrays
  • Divide and Conquer
  • Java
  • python
  • Recursion

Similar Reads

  • Smallest integer > 1 which divides every element of the given array
    Given an array arr[], the task is to find the smallest possible integer (other than 1) which divides every element of the given array. Examples: Input: arr[] = { 2, 4, 8 } Output: 2 2 is the smallest possible number which divides the whole array. Input: arr[] = { 4, 7, 5 } Output: -1 There's no inte
    13 min read
  • Find elements of an array which are divisible by N using STL in C++
    Given an array and an integer N, find elements which are divisible by N, using STL in C++ Examples: Input: a[] = {1, 2, 3, 4, 5, 10}, N = 2 Output: 3 Explanation: As 2, 4, and 10 are divisible by 2 Therefore the output is 3 Input:a[] = {4, 3, 5, 9, 11}, N = 5 Output: 1 Explanation: As only 5 is divi
    2 min read
  • C++ Program to Find the Frequency of Elements in an Array
    In C++, arrays are a type of data structure that can store a fixed-size sequential collection of elements of the same type. In this article, we will learn how to find the frequency of elements in an array in C++. Example: Input: Array: {1, 2, 3, 4, 2, 1, 3, 2, 4, 5} Output: Element: 1, Frequency: 2
    2 min read
  • C program to count frequency of each element in an array
    Given an array arr[] of size N, the task is to find the frequency of each distinct element present in the given array. Examples: Input: arr[] = { 1, 100000000, 3, 100000000, 3 } Output: { 1 : 1, 3 : 2, 100000000 : 2 } Explanation: Distinct elements of the given array are { 1, 100000000, 3 } Frequenc
    4 min read
  • Count of elements not divisible by any other elements of Array
    Given an array arr[], the task is to determine the number of elements of the array which are not divisible by any other element in the given array. Examples: Input: arr[] = {86, 45, 18, 4, 8, 28, 19, 33, 2} Output: 4 Explanation: The elements are {2, 19, 33, 45} are not divisible by any other array
    13 min read
  • First element that appears even number of times in an array
    Given an array, find the first element that appears even number of times in the array. It returns the element if exists otherwise returns 0. Examples: Input : arr[] = {1, 5, 4, 7, 4, 1, 5, 7, 1, 5}; Output : 4 Explanation, 4 is the first element that appears even number of times. Input : arr[] = {2,
    7 min read
  • Count integers in an Array which are multiples their bits counts
    Given an array arr[] of N elements, the task is to count all the elements which are a multiple of their set bits count.Examples: Input : arr[] = { 1, 2, 3, 4, 5, 6 } Output : 4 Explanation : There numbers which are multiple of their setbits count are { 1, 2, 4, 6 }. Input : arr[] = {10, 20, 30, 40}
    9 min read
  • Frequency of each element of an array of small ranged values
    Given an array where elements in small range. The maximum element in the array does not go beyond size of array. Find frequencies of elements. Examples: Input : arr[] = {3, 1, 2, 3, 4, 5, 4} Output: 1-->1 2-->1 3-->2 4-->2 5-->1 Input : arr[] = {1, 2, 2, 1, 2} Output: 1-->2 2-->
    6 min read
  • Find the element having different frequency than other array elements
    Given an array of N integers. Each element in the array occurs the same number of times except one element. The task is to find this element. Examples: Input : arr[] = {1, 1, 2, 2, 3}Output : 3Input : arr[] = {0, 1, 2, 4, 4}Output : 4The idea is to use a hash table freq to store the frequencies of g
    8 min read
  • Maximize frequency of an element by at most one increment or decrement of all array elements
    Given an array arr[] of size N, the task is to find the maximum frequency of any array element by incrementing or decrementing each array element by 1 at most once. Examples: Input: arr[] = { 3, 1, 4, 1, 5, 9, 2 } Output: 4 Explanation: Decrementing the value of arr[0] by 1 modifies arr[] to { 2, 1,
    8 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