Remove Duplicate Characters from a String

Code

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

void remove_duplicates(char *str) {
    uint8_t i = 0, j = 0;
    char seen[256] = {0};  // ASCII character map

    while (str[i]) {
        if (!seen[(uint8_t)str[i]]) {
            seen[(uint8_t)str[i]] = 1;
            str[j++] = str[i];
        }
        i++;
    }
    str[j] = '\0';  // Null-terminate the result
}

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

1. Track seen characters

  • Use a fixed-size array seen[256] to represent all possible ASCII characters.
  • Each index corresponds to a character (seen['e'], seen['m'], etc.).
  • Initialize all entries to 0.

2. Iterate through the input string

  • Use two pointers:
  • i: scans the original string
  • j: builds the result in-place

3. Check if character is already seen

  • If seen[str[i]] == 0, it’s the first time we’ve seen this character:
    • Set seen[str[i]] = 1
    • Copy str[i] to str[j]
    • Increment j
  • If seen[str[i]] == 1, skip it.

4. Terminate the result

  • After the loop, set str[j] = '\0' to properly end the string.

 

🧩 Embedded-Friendly Notes

  • No dynamic memory
  • No string libraries
  • Works in-place — no extra string buffer
  • Uses only char, uint8_t, and fixed-size arrays

 

 

Upvote
Downvote
Loading...

Input

programming

Expected Output

progamin