C Example Code2026-03-201 min read
Remove duplicate characters from a string in C using a frequency hash map and two pointers with O(n) linear time complexity.
Algorithm Approach
Using a boolean lookup array representing the 256 possible ASCII character codes, we can track seen characters in O(1) time and modify the string in-place with a write pointer:
Complete C Code
c (ISO Standard)#include <stdio.h> #include <stdbool.h> void removeDuplicates(char *str) { if (str == NULL) return; bool seen[256] = {false}; int readIdx = 0; int writeIdx = 0; while (str[readIdx] != '\0') { unsigned char ch = (unsigned char)str[readIdx]; if (!seen[ch]) { seen[ch] = true; str[writeIdx++] = str[readIdx]; } readIdx++; } str[writeIdx] = '\0'; /* Null terminate the modified string */ } int main() { char sample[] = "programming in c language"; printf("Original String: \"%s\"\n", sample); removeDuplicates(sample); printf("Without Duplicates: \"%s\"\n", sample); return 0; }
Sample Output
text (ISO Standard)Original String: "programming in c language" Without Duplicates: "progamin c lue"
Complexity Analysis
- Time Complexity:
O(n)single-pass linear time. - Auxiliary Space:
O(1)(Fixed 256-byte ASCII array).
Related Programs
- Character analysis in Count Vowels and Consonants in C.
- Master array allocations in Arrays in C Programming.