- Related Questions & Answers
- Find duplicates in O(n) time and O(1) extra space - Set 1 in C++
- Find maximum in a stack in O(1) time and O(1) extra space in C++
- Find duplicate in an array in O(n) and by using O(1) extra space in C++
- Print left rotation of array in O(n) time and O(1) space in C Program.
- Find median of BST in O(n) time and O(1) space in C++
- Count Fibonacci numbers in given range in O(Log n) time and O(1) space in C++
- Print n x n spiral matrix using O(1) extra space in C Program.
- Check for balanced parentheses in an expression - O(1) space - O(N^2) time complexity in C++
- Find duplicates in constant array with elements 0 to N-1 in O(1) space in C++
- A product array puzzle (O(1) Space) in C++?
- C++ function to count nodes in O(1) constant time
- A data structure for n elements and O(1) operations?
- Count frequencies of all elements in array in Python
- Count frequencies of all elements in array in Python using collections module
- Comparison of memory-mapped I/O and I/O-mapped I/O

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

We are given with an array of elements ranging from values 1 to n. Some elements are repeated, and some are missing. The goal is to find the frequencies of all elements in O(n) time and O(1) extra space.

Arr[]= { 1,2,2,3,4,4,4,5 }

1→ 1, 2 → 2, 3→ 1, 4→ 3, 5→ 5

**Explanation** − The highest element is 5, the output shows the number of times each element appears in the array.

Arr[]= { 1,4,4,5,5,5,5 }

1→ 1, 2 →0, 3→ 0, 4→ 2, 5→ 4

**Explanation** − The highest element is 5, the output shows the number of times each element appears in the array.

Below program works for arrays with numbers between 1 to 10.

Function printfrequency(int arr[],int n) takes an array and its size n as input and returns the count of numbers between 1 to 10 present in the array.

We make arr[i]=arr[i]-1 so that each index stores the frequency of number i, 1 stored at index 0 and so on.

Using for loop at each frequency arr[arr[i]%10] add 10 to the original value.

For x times 10 will be added if number i occurs x times in array.

Now using for loop print frequencies using arr[i]/10 for all elements i+1 at index i.

#include<bits/stdc++.h> using namespace std; void printfrequency(int arr[],int n){ int i=0; //1 becomes 0, 2 becomes 1 .....10 becomes 9 so arr[i] will have count of i for ( i =0; i<n; i++) arr[i] = arr[i]-1; //as numbers are between 1-10 add 10 to all (num%10 is num itself) for (i=0; i<n; i++) arr[arr[i]%10] = arr[arr[i]%10] + 10; for (i =0; i<10; i++) cout << i + 1 << " -> " << arr[i]/10 << endl; } int main(){ int arr[] = {2, 3, 3, 2, 5, 6, 7, 7, 7, 8, 8, 9, 9}; int n = sizeof(arr)/sizeof(arr[0]); printfrequency(arr,n); return 0; }

1 -> 0 2 -> 2 3 -> 2 4 -> 0 5 -> 1 6 -> 1 7 -> 3 8 -> 2 9 -> 5 10 -> 0

Advertisements