- Related Questions & Answers
- C++ Program to Implement Sorting of Less than 100 Numbers in O(n) Complexity
- Find element in a sorted array whose frequency is greater than or equal to n/2 in C++.
- Find median of BST in O(n) time and O(1) space in C++
- C++ program to find unique pairs such that each element is less than or equal to N
- Find the element having different frequency than other array elements in C++
- Find frequency of each word in a string in C#
- Count Fibonacci numbers in given range in O(Log n) time and O(1) space in C++
- Find median of BST in O(n) time and O(1) space in Python
- Print left rotation of array in O(n) time and O(1) space in C Program.
- Find duplicates in O(n) time and O(1) extra space - Set 1 in C++
- Count frequencies of all elements in array in O(1) extra space and O(n) time in C++
- Find Surpasser Count of each element in array in C++
- Generate a list of Primes less than n in Python
- Find all factorial numbers less than or equal to n in C++
- Find duplicates in a given array when elements are not limited to a range in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have an array of integers. The array is A, and the size is n. Our task is to find the frequency of all elements in the array less than O(n) time. The size of the elements must be less than one value say M. Here we will use the binary search approach. Here we will recursively divide the array into two parts if the end elements are different, if both its end elements are the same, it means all elements in the array are the same as the array is already sorted.

#include<iostream> #include<vector> using namespace std; void calculateFreq(int arr[], int left, int right, vector<int>& frequency) { if (arr[left] == arr[right]) frequency[arr[left]] += right - left + 1; else { int mid = (left + right) / 2; calculateFreq(arr, left, mid, frequency); calculateFreq(arr, mid + 1, right, frequency); } } void getAllFrequency(int arr[], int n) { vector<int> frequency(arr[n - 1] + 1, 0); calculateFreq(arr, 0, n - 1, frequency); for (int i = 0; i <= arr[n - 1]; i++) if (frequency[i] != 0) cout << "Frequency of element " << i << " is " << frequency[i] << endl; } int main() { int arr[] = { 10, 10, 10, 20, 30, 30, 50, 50, 80, 80, 80, 90, 90, 99 }; int n = sizeof(arr) / sizeof(arr[0]); getAllFrequency(arr, n); }

Frequency of element 10 is 3 Frequency of element 20 is 1 Frequency of element 30 is 2 Frequency of element 50 is 2 Frequency of element 80 is 3 Frequency of element 90 is 2 Frequency of element 99 is 1

Advertisements