All submissions

Remove Duplicate Characters from a String

Code

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

void remove_duplicates(char *str) 
{
    int i,j,k;
    int n = strlen(str);
     for (i = 0; i < n; i++) {
        for (j = i + 1; str[j] != '\0'; j++) {
            // If a duplicate character is found
            if (str[i] == str[j]) {
                // Shift all subsequent characters to the left
                for (k = j; str[k] != '\0'; k++) {
                    str[k] = str[k + 1];
                }
                str[n - 1] = '\0'; // Null-terminate the string after shifting
                n--; // Decrease the length of the string
                j--; // Decrement j to re-check the character at the current position
                     // as a new character has shifted into this position
            }
        }
    }
}

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

 

 

 

Loading...

Input

programming

Expected Output

progamin