Algorithm to find repetition of elements in array

Case 1: When range of elements is given

Take an array count depending on the range of elements and initialize every element as zero. Traverse the entire unsorted / sorted array, keep track of count of all elements if you find any element whose count is not zero, then print that element as repeating element.
Implementation in C:

#include<stdio.h>
#include<stdlib.h>
void repeat(int*, int);
int main()
 {
  int arr[] = {4, 5, 6, 5, 3, 1};
  int arr_size = sizeof(arr) / sizeof(arr[0]) ;
  repeat(arr, arr_size);
  return 0;
 }

void repeat(int arr[], int size)
 {
  int *count = (int*) calloc(sizeof(int), (size-2) );
  int i, flag =0;
  for(i=0;i<size;i++)
  {
    if (count[arr[i]] == 0)
      count[arr[i]] = 1;
   else
      flag = 1;
  }
 if(flag == 0)
  printf("\nAll unique elements are present in array");
 else
  printf("\nThere is repetition in elements");

 }

Time Complexity: O(n)
Space Complexity: O(n)

Case 2: When range of elements is not given

Approach: First, sort the array. Then check side by side elements while traversing through the array.

Implementation in C: Later on.

Time Complexity: O(n log n)
Space Complexity: O(1)

Comments

Popular posts from this blog

Three mislabeled Jar

Difference between Macro And function