Remove Duplicate Characters from a String

Code

#include <stdio.h>
#include <stdint.h>

void remove_duplicates( char arr[]){

    int hash[256]={0};
    int write=0;

    for(int i=0;arr[i]!='\0';i++){
        int ch=arr[i];
        if(!hash[ch]){
            hash[ch]=1;
            arr[write++]= arr[i];
        }
    }

    arr[write]='\0';

}

/*
if you want it in O(n) and O(1) space, just for lowercase, 
using masking

void remove_duplicaes(char *str){
int mask =0;

int i=0,j=0;

while(str[i]){
    int bit = str[i]-'a';

    if(!(mask & (1<<bit))){
        mask|= (1<<bit);

        str[j++]=str[i];
    }
        i++;
    }

    str[i]
}

*/

int main() {
    char str[101];
    fgets(str, sizeof(str), stdin);

    // Remove newline
    uint8_t i = 0;
    while (str[i]) {
        if (str[i] == '\n') {
            str[i] = '\0';
            break;
        }
        i++;
    }

    remove_duplicates(str);
    printf("%s", str);
    return 0;
}


///////////

// void remove_duplicates(char *str) {
//     uint8_t hash[256] = {0};  // 1-byte flags per ASCII char
//     uint8_t read = 0, write = 0;

//     while (str[read] != '\0') {
//         uint8_t ch = (uint8_t)str[read];
//         if (!hash[ch]) {
//             hash[ch] = 1;
//             str[write++] = str[read];
//         }
//         read++;
//     }
//     str[write] = '\0';  // Null terminate final string
// }



Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

programming

Expected Output

progamin