Monday, 9 November 2015

Remove all duplicates from a given string

Below are the different methods to remove duplicates in a string.
METHOD 1 (Use Sorting)
Algorithm:
  1) Sort the elements.
  2) Now in a loop, remove duplicates by comparing the 
      current character with previous character.
  3)  Remove extra characters at the end of the resultant string.

Example:
Input string:  geeksforgeeks
1) Sort the characters
   eeeefggkkosss
2) Remove duplicates
    efgkosgkkosss
3) Remove extra characters
     efgkos
Note that, this method doesn’t keep the original order of the input string. For example, if we are to remove duplicates for geeksforgeeks and keep the order of characters same, then output should be geksfor, but above function returns efgkos. We can modify this method by storing the original order. METHOD 2 keeps the order same.
Implementation:
// C++ prigram to remove duplicates, the order of
// characters is not maintained in this program
#include<bits/stdc++.h>
using namespace std;
 
/* Function to remove duplicates in a sorted array */
char *removeDupsSorted(char *str)
{
    int res_ind = 1, ip_ind = 1;
 
    /* In place removal of duplicate characters*/
    while (*(str + ip_ind))
    {
        if (*(str + ip_ind) != *(str + ip_ind - 1))
        {
            *(str + res_ind) = *(str + ip_ind);
            res_ind++;
        }
        ip_ind++;
    }
 
    /* After above step string is stringiittg.
       Removing extra iittg after string*/
    *(str + res_ind) = '\0';
 
    return str;
}
 
 
/* Function removes duplicate characters from the string
   This function work in-place and fills null characters
   in the extra space left */
char *removeDups(char *str)
{
   int n = strlen(str);
 
   // Sort the character array
   sort(str, str+n);
 
   // Remove duplicates from sorted
   return removeDupsSorted(str);
}
 
/* Driver program to test removeDups */
int main()
{
  char str[] = "eeeefggkkosss";
  cout << removeDups(str);
  return 0;
}

Output:
efgkos
Time Complexity: O(nlogn) If we use some nlogn sorting algorithm instead of quicksort.


METHOD 2 (Use Hashing )
Algorithm:
1: Initialize:
    str  =  "test string" /* input string */
    ip_ind =  0          /* index to  keep track of location of next
                             character in input string */
    res_ind  =  0         /* index to  keep track of location of
                            next character in the resultant string */
    bin_hash[0..255] = {0,0, ….} /* Binary hash to see if character is 
                                        already processed or not */
2: Do following for each character *(str + ip_ind) in input string:
              (a) if bin_hash is not set for *(str + ip_ind) then
                   // if program sees the character *(str + ip_ind) first time
                         (i)  Set bin_hash for *(str + ip_ind)
                         (ii)  Move *(str  + ip_ind) to the resultant string.
                              This is done in-place.
                         (iii) res_ind++
              (b) ip_ind++
  /* String obtained after this step is "te sringng" */
3: Remove extra characters at the end of the resultant string.
  /*  String obtained after this step is "te sring" */
Implementation:
# include <stdio.h>
# include <stdlib.h>
# define NO_OF_CHARS 256
# define bool int
 
/* Function removes duplicate characters from the string
   This function work in-place and fills null characters
   in the extra space left */
char *removeDups(char *str)
{
  bool bin_hash[NO_OF_CHARS] = {0};
  int ip_ind = 0, res_ind = 0;
  char temp;   
 
  /* In place removal of duplicate characters*/ 
  while (*(str + ip_ind))
  {
    temp = *(str + ip_ind);
    if (bin_hash[temp] == 0)
    {
        bin_hash[temp] = 1;
        *(str + res_ind) = *(str + ip_ind);
        res_ind++;        
    }
    ip_ind++;
  }     
 
  /* After above step string is stringiittg.
     Removing extra iittg after string*/       
  *(str+res_ind) = '\0';  
   
  return str;
}
 
/* Driver program to test removeDups */
int main()
{
    char str[] = "geeksforgeeks";
    printf("%s", removeDups(str));
    getchar();
    return 0;
}
Output:
gksfor

Time Complexity: O(n)
NOTES:
* Method 1 doesn’t maintain order of characters as original string, but method 2 does.
* It is assumed that number of possible characters in input string are 256. NO_OF_CHARS should be changed accordingly.
* calloc is used instead of malloc for memory allocations of counting array (count) to initialize allocated memory to ‘\0′. malloc() followed by memset() could also be used.
* Above algorithm also works for an integer array inputs if range of the integers in array is given. Example problem is to find maximum occurring number in an input array given that the input array contain integers only between 1000 to 1100

No comments:

Post a Comment