2
Remove duplicates from string 1) without using any additional buffer 2) using one additional buffer
String
Duplicate-removal

Algorithm without using additional buffer:-

1) For each character, check if it is a duplicate of already found character.

2) Skip duplicate character and update non-duplicate character.

Source Code in C:-

#include<stdio.h>
#include<string.h>

void removeDup(char *str)
{
        int i = 0;
        if (str == NULL)
                return;
        int len = strlen(str);

        if (len < 2) return;
        int tail = 1;
        for (i = 1; i < len; ++i)
        {
                int j;
                for (j = 0; j < tail; ++j)
                {
                        if (str[i] == str[j])
                                break;
                }
                if (j == tail)
                {
                        str[tail] = str[i];
                        ++tail;
                }
        }
        str[tail] = 0;
        printf("string after removal of duplicates is:%s",str);
}

int main()
{
        char str[]="abababcdfef";
        removeDup(str);
        return 0;
}

Output:-

string after removal of duplicates is:abcdfe

Algorithm with additional buffer:- 1) Take an additional buffer and initialize with null.

2) Traverse the string and for each character,check whether corresponding index in additional taken buffer is already marked or not. if its already marked mean that character is already found (duplicate) so skip it, and if its not marked means that character is not already found (non-duplicate) consider it and update the string

#include<stdio.h>
#include <string.h>
void removeDuplicatesEff(char *str)
{
        int i = 0;
        if (str == NULL)
                return;
        int len = strlen(str);
        if (len < 2)
                return;
        char hit[256];
        for ( i = 0; i < 256; ++i)
        {
                hit[i] = 0;
        }
        hit[str[0]] = 1;
        int tail = 1;
        for ( i = 1; i < len; ++i)
        {
                if (!hit[str[i]])
                {
                        str[tail] = str[i];
                        ++tail;
                        hit[str[i]] = 1;

                }
        }
        str[tail] = 0;
        printf("string after removal of duplicate is :%s",str);
}

int main()
{
        char str[]="abababaefafe";
        removeDuplicatesEff(str);
        return 0;
}

output:-

abef

Test cases for above algorithm :-

1) string is NULL.

2) string contains only one character.

3) string having no duplicates ex:- abcdefgh

4) string contains all duplicate Ex:- aaaaa

5) string containing all continuous duplicate. Ex:- aaaabbb

6) string containing non-continuous duplicate. Ex:- ababab

Author

Notifications

?