Spread the love

Write a C Program to Print all the Repeated Numbers with Frequency in Array. So first approach is to use linear search and find the occurrence of numbers but efficient solution is to use less time and space complexity.

For Example if you given array A[ ] = { 5, 3, 2, 5, 3, 1}; to find frequency of numbers, So here is small solution with  Time and Space complexity with O(n) .

/* Solution in two line  */
for(int i=0; i<SIZE; i++)
	OccurCount[A[i]]++;

 

Here array A is our main array in which we want to find frequency of numbers and array OccurCount is used to count element occurrences.

Logic

The logic of this problem is pretty simple

  1. We declare new array OccurCount of same size as A.
  2. Increment the value in OccurCount array at index same as element. For example if we get first element ‘5’ in array A , then increment value of element in array OccurCount at index 5.

C Program to Print all the Repeated Numbers with Frequency in Array

#include <stdio.h>

#define SIZE 6

int main()
{
	int A[SIZE] = {1,2,1,4,1,4};			// Main array to search occurrence

	int OccurCount[SIZE]={0,0,0,0,0,0};		// make zero each element otherwise you will see garbage value in output

	/* Solution in two line  */
	for(int i=0; i<SIZE; i++)
		OccurCount[A[i]]++;
		
	/* Print element occurrences */	
	for(int i=0; i<SIZE; i++)
		printf(" %d is occur %d times \n",i,OccurCount[i]);
		
	return 0;	
}

 

Output

C Program to Print all the Repeated Numbers with Frequency in Array