Saturday, December 4, 2021
HomeTop Coding QuestionWrite a program to find duplicate number on a given array.

Write a program to find duplicate number on a given array.

Given an integer array , we have to find duplicate element on a given array.and print the value.

Example:

input:1 1 2 2 3 4
output:1 2

Logic:

step 1-create a map, and count the frequency of array.
step 2-if the frequency of array is greater than 1,then print the result. 

Code-

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int arr[]={1,1,2,2,3,4};
    int n=sizeof(arr)/sizeof(arr[0]);
   map<int,int>m;
   for(int i=0;i<n;i++)
   {
       m[arr[i]]++;
   }
   for(auto i=m.begin();i!=m.end();i++)
   {
       if(i->second>1)
       {
       cout<<i->first<<" ";
       }
   }
   cout<<endl;
    
    
}

Output:

1 2

Time complexity:0(N)

Space Complexity:O(N)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments