Adsense 728 * 15

Search

Custom Search

Program to Print Duplicate Element of an Array - C, C++ Code

Write a C, C++ program to print a duplicate element of an array. Given an array, Only one element in an array is repeated, print a duplicate element.

C, C++ Interview Questions


Method 1 - Naive Approach

Use two for loops, Compare each element of an array with other element. The time complexity of this approach is  O(n2).

C Program to Print Duplicate Element in an Array



 #include <stdio.h>

  int main(void) {
 
     int arr[100], i, j, size;
   
     printf("Enter the size of an array \n");
     scanf("%d",&size);
   
     printf("Enter the elements in an array\n");
   
     for( i = 0; i < size; i++) {
        scanf("%d", &arr[i]);
     }
  
     /* Logic to print duplicate
        element of an array */
      
      for(i = 0; i < size; i++){
         for(j=i+1; j < size; j++){
   
           if(arr[i] == arr[j]){
    
              printf("Duplicate element in an array is %d ",arr[i]);
              break;
            }
         }
      }
    
      return 0;
 }


Output -

Enter the size of an array   5

Enter the elements in an array  2   3   6   5   3

Duplicate element in an array is  5



Method 2 - Use hashing

In this approach, We are using C++ map library. The time complexity of this program is O(n).


C ++ code to Find Duplicate Element in Array



#include <iostream>
#include <map>

using namespace std;

int main() {
 
   int arr[100], i, size;
   
   cout <<"Enter the size of an array\n";
   cin  >> size;
   
   cout <<"Enter elements in an array \n";
   
   for(i = 0; i < size; i++) {
       cin >> arr[i];
   }

    // Map STL library implementation
    map<int, int> hash;
   
   
   /* Make key and value pair.
      key denotes the element
      value is the count of that element.
   */ 
    for(i = 0; i < size; i++) {
      hash[arr[i]] = hash[arr[i]] + 1;  
    }
  
  
   /* Check the count and if 
      count is greater than 1 then 
      print the element */

    for(i = 0; i < size; i++){

        if (hash[arr[i]] > 1){
          cout<<"Repeated element is "<< arr[i];
          break;
        }
    }
    
    return 0;
}


Programming questions on strings

Sorting algorithm and their implementation

Search algorithm

Question on arrays

No comments:

Post a Comment