Pages

Subscribe:

Blogger templates

Thursday, July 21, 2016

Remove Duplicate Elements

Naive Approach
Removing duplicate letter from a String
------------------------------------------------

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27


#include<string.h>
#include<stdio.h>
char str[] = "ncertcppblogger";
void shift(int i){
   do{
        str[i]=str[i+1];
        i++;
    } while(str[i]!='\0');
}
void removeDups(){
    int i,j;
   for(i=0;i<strlen(str);i++){
       for(j=i+1;j<strlen(str);j++){
           if(str[i]==str[j]){
               shift(j);
               j=i+1;
           }
       }
   }
   printf("%s",str);
}
int main(){
     
    removeDups();
    return 0;
     
}


OUTPUT

ncertpblog


RUN THIS



HASHING APPROACH

Complexity O(n)
----------------


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include<bits/stdc++.h>
using namespace std;
unordered_set <int> s;
int a[10]={3, 5, 7, 3, 3, 13, 5, 13, 29, 13};
void shift(int i){
    do{
         
        a[i]=a[i+1];
        i++;
         
    }while(i!=10);
}
int main(){
    int tot=0;
    for(int i=0;i<10-tot;i++){
        if(s.find(a[i])!=s.end()){
            tot++;
            shift(i);
            i--;
            
        }
        else{
            s.insert(a[i]);
        }
    }
     
    //printing
    for(int j=0;j<10-tot;j++){
        printf("%d ",a[j]);
    }
     
     
     
     
     
     
     
     
     
    return 0;
}


RUN THIS