Remove Duplicate Characters from a String

Code

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

void remove_duplicates(char *str) {
	//Your logic here
    char str2[101];
    int freq[26] = {0};
    int i=0, top = 0;
    while(str[i]!= '\0')
    {
        if(str[i] - 97 >=0)
        {
            if(freq[str[i] - 97] == 0)
            {   
                freq[str[i] - 97]+=1;
                str2[top++] = str[i];
            }   
            
        }
        else if(str[i] - 65 >=0 )
        {
            if(freq[str[i] - 65] >= 0)
            {
                freq[str[i] - 65]+=1;
                str2[top++] = str[i];
            }
        }
        else if(str[i] >= '0' && str[i] <= '9')
        {
            if(freq[str[i] - 48]==0)
            {
                freq[str[i] - 48]+=1;
                str2[top++] = str[i];
            }
        }
        else
            str2[top++] = str[i];

        i++;        
    }
    for(int x=0;x<top;x++)
        str[x] = str2[x];
    str[top] = '\0';
}

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;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

programming

Expected Output

progamin