Remove duplicates from a given string

06 Jul, 2022
C++
Java
Python3
C#
Javascript
// CPP program to remove duplicate character// from character array and print in sorted// order#include <bits/stdc++.h>using namespace std; char *removeDuplicate(char str[], int n){    // create a set using string characters    // excluding '\0'    unordered_set<char>s (str, str+n-1);     // print content of the set    int i = 0;    for (auto x : s)       str[i++] = x;    str[i] = '\0';     return str;} // Driver codeint main(){   char str[]= "geeksforgeeks";   int n = sizeof(str) / sizeof(str[0]);   cout << removeDuplicate(str, n);   return 0;}
// Java program to remove duplicate character// from character array and print in sorted// orderimport java.util.*; class GFG {         static void removeDuplicate(char str[], int n)    {       // Create a set using String characters    // excluding '\0'        HashSet<Character> s = new LinkedHashSet<>(n - 1);      // HashSet doesn't allow repetition of elements        for (char x : str)            s.add(x);         // Print content of the set        for (char x : s)            System.out.print(x);    }     // Driver code    public static void main(String[] args)    {        char str[] = "geeksforgeeks".toCharArray();        int n = str.length;         removeDuplicate(str, n);    }} // This code is contributed by todaysgaurav
# Python program to remove duplicate character# from character array and print in sorted# orderdef removeDuplicate(str, n):    s = set()         # Create a set using String characters    for i in str:        s.add(i)     # Print content of the set    st = ""    for i in s:        st = st+i    return st  # Driver codestr = "geeksforgeeks"n = len(str)print(removeDuplicate(list(str), n)) # This code is contributed by rajsanghavi9.
// C# program to remove duplicate character// from character array and print in sorted// orderusing System;using System.Collections.Generic;  public class GFG{ static char []removeDuplicate(char []str, int n){         // Create a set using String characters    // excluding '\0'    HashSet<char>s = new HashSet<char>(n - 1);    foreach(char x in str)        s.Add(x);             char[] st = new char[s.Count];         // Print content of the set    int i = 0;    foreach(char x in s)       st[i++] = x;       return st;} // Driver codepublic static void Main(String[] args){   char []str= "geeksforgeeks".ToCharArray();   int n = str.Length;       Console.Write(removeDuplicate(str, n));}} // This code contributed by gauravrajput1
<script>// javascript program to remove duplicate character// from character array and print in sorted// order     function removeDuplicate( str , n)    {             // Create a set using String characters        // excluding '\0'        var s = new Set();                 // HashSet doesn't allow repetition of elements        for (var i = 0;i<n;i++)            s.add(str[i]);         // Print content of the set        for (const v of s) {             document.write(v);    }    }     // Driver code        var str = "geeksforgeeks";        var n = str.length;         removeDuplicate(str, n); // This code is contributed by umadevi9616</script>
Given a string S, the task is to remove all the duplicates in the given string. Below are the different methods to remove duplicates in a string.
METHOD 1 (Simple) 
C++
Java
Python3
C#
Javascript
// CPP program to remove duplicate character// from character array and print in sorted// order#include <bits/stdc++.h>using namespace std; char *removeDuplicate(char str[], int n){   // Used as index in the modified string   int index = 0;         // Traverse through all characters   for (int i=0; i<n; i++) {             // Check if str[i] is present before it      int j;      for (j=0; j<i; j++)        if (str[i] == str[j])           break;           // If not present, then add it to     // result.     if (j == i)        str[index++] = str[i];   }       return str;} // Driver codeint main(){   char str[]= "geeksforgeeks";   int n = sizeof(str) / sizeof(str[0]);   cout << removeDuplicate(str, n);   return 0;}
// Java program to remove duplicate character// from character array and print in sorted// orderimport java.util.*; class GFG{    static String removeDuplicate(char str[], int n)    {        // Used as index in the modified string        int index = 0;         // Traverse through all characters        for (int i = 0; i < n; i++)        {             // Check if str[i] is present before it            int j;            for (j = 0; j < i; j++)            {                if (str[i] == str[j])                {                    break;                }            }             // If not present, then add it to            // result.            if (j == i)            {                str[index++] = str[i];            }        }        return String.valueOf(Arrays.copyOf(str, index));    }     // Driver code    public static void main(String[] args)    {        char str[] = "geeksforgeeks".toCharArray();        int n = str.length;        System.out.println(removeDuplicate(str, n));    }} // This code is contributed by Rajput-Ji
string="geeksforgeeks"p=""for char in string:    if char not in p:        p=p+charprint(p)k=list("geeksforgeeks")
// C# program to remove duplicate character// from character array and print in sorted// orderusing System;using System.Collections.Generic;class GFG{static String removeDuplicate(char []str, int n){    // Used as index in the modified string    int index = 0;     // Traverse through all characters    for (int i = 0; i < n; i++)    {         // Check if str[i] is present before it        int j;        for (j = 0; j < i; j++)        {            if (str[i] == str[j])            {                break;            }        }         // If not present, then add it to        // result.        if (j == i)        {            str[index++] = str[i];        }    }    char [] ans = new char[index];    Array.Copy(str, ans, index);    return String.Join("", ans);} // Driver codepublic static void Main(String[] args){    char []str = "geeksforgeeks".ToCharArray();    int n = str.Length;    Console.WriteLine(removeDuplicate(str, n));}} // This code is contributed by PrinciRaj1992
<script> // JavaScript program to remove duplicate character// from character array and print in sorted// orderfunction removeDuplicate(str, n)    {        // Used as index in the modified string        var index = 0;         // Traverse through all characters        for (var i = 0; i < n; i++)        {             // Check if str[i] is present before it            var j;            for (j = 0; j < i; j++)            {                if (str[i] == str[j])                {                    break;                }            }             // If not present, then add it to            // result.            if (j == i)            {                str[index++] = str[i];            }        }                 return str.join("").slice(str, index);    }     // Driver code        var str = "geeksforgeeks".split("");        var n = str.length;        document.write(removeDuplicate(str, n));     // This code is contributed by shivanisinghss2110 </script>
Output:  
geksfor
Time Complexity: O(n * n) Auxiliary Space: O(1) Keeps order of elements the same as the input. 
METHOD 2 (using set)Use set to store only one instance of any value. 
C++
Java
Python3
C#
Javascript
// CPP program to remove duplicate character// from character array and print in sorted// order#include <bits/stdc++.h>using namespace std; char *removeDuplicate(char str[], int n){    // create a set using string characters    // excluding '\0'    unordered_set<char>s (str, str+n-1);     // print content of the set    int i = 0;    for (auto x : s)       str[i++] = x;    str[i] = '\0';     return str;} // Driver codeint main(){   char str[]= "geeksforgeeks";   int n = sizeof(str) / sizeof(str[0]);   cout << removeDuplicate(str, n);   return 0;}
// Java program to remove duplicate character// from character array and print in sorted// orderimport java.util.*; class GFG {         static void removeDuplicate(char str[], int n)    {       // Create a set using String characters    // excluding '\0'        HashSet<Character> s = new LinkedHashSet<>(n - 1);      // HashSet doesn't allow repetition of elements        for (char x : str)            s.add(x);         // Print content of the set        for (char x : s)            System.out.print(x);    }     // Driver code    public static void main(String[] args)    {        char str[] = "geeksforgeeks".toCharArray();        int n = str.length;         removeDuplicate(str, n);    }} // This code is contributed by todaysgaurav
# Python program to remove duplicate character# from character array and print in sorted# orderdef removeDuplicate(str, n):    s = set()         # Create a set using String characters    for i in str:        s.add(i)     # Print content of the set    st = ""    for i in s:        st = st+i    return st  # Driver codestr = "geeksforgeeks"n = len(str)print(removeDuplicate(list(str), n)) # This code is contributed by rajsanghavi9.
// C# program to remove duplicate character// from character array and print in sorted// orderusing System;using System.Collections.Generic;  public class GFG{ static char []removeDuplicate(char []str, int n){         // Create a set using String characters    // excluding '\0'    HashSet<char>s = new HashSet<char>(n - 1);    foreach(char x in str)        s.Add(x);             char[] st = new char[s.Count];         // Print content of the set    int i = 0;    foreach(char x in s)       st[i++] = x;       return st;} // Driver codepublic static void Main(String[] args){   char []str= "geeksforgeeks".ToCharArray();   int n = str.Length;       Console.Write(removeDuplicate(str, n));}} // This code contributed by gauravrajput1
<script>// javascript program to remove duplicate character// from character array and print in sorted// order     function removeDuplicate( str , n)    {             // Create a set using String characters        // excluding '\0'        var s = new Set();                 // HashSet doesn't allow repetition of elements        for (var i = 0;i<n;i++)            s.add(str[i]);         // Print content of the set        for (const v of s) {             document.write(v);    }    }     // Driver code        var str = "geeksforgeeks";        var n = str.length;         removeDuplicate(str, n); // This code is contributed by umadevi9616</script>
Output:  
  efgkors
Time Complexity: O(n) Auxiliary Space: O(n)
Thanks to Anivesh Tiwari for suggesting this approach.
It does not keep the order of elements the same as the input but prints them in sorted order.
METHOD 3 (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
   eeeefggkkorss
2) Remove duplicates
    efgkorskkorss
3) Remove extra characters
     efgkors
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 the same, then the output should be geksfor, but the above function returns efgkos. We can modify this method by storing the original order.
Implementation:  
C++
C
Java
Python3
C#
Javascript
// C++ program 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 efgkorskkorss.       Removing extra kkorss 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[] = "geeksforgeeks";  cout << removeDups(str);  return 0;}
// C program to remove duplicates, the order of// characters is not maintained in this program# include <stdio.h># include <stdlib.h># include <string.h>/* Function to remove duplicates in a sorted array */char *removeDupsSorted(char *str); /* Utility function to sort array A[] */void quickSort(char A[], int si, int ei); /* 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 len = strlen(str);  quickSort(str, 0, len-1);  return removeDupsSorted(str);}     /* 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 efgkorskkorss.     Removing extra kkorss 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;} /* FOLLOWING FUNCTIONS ARE ONLY FOR SORTING    PURPOSE */void exchange(char *a, char *b){  char temp;  temp = *a;  *a   = *b;  *b   = temp;} int partition(char A[], int si, int ei){  char x = A[ei];  int i = (si - 1);  int j;   for (j = si; j <= ei - 1; j++)  {    if (A[j] <= x)    {      i++;      exchange(&A[i], &A[j]);    }  }  exchange (&A[i + 1], &A[ei]);  return (i + 1);} /* Implementation of Quick SortA[] --> Array to be sortedsi  --> Starting indexei  --> Ending index*/void quickSort(char A[], int si, int ei){  int pi;    /* Partitioning index */  if (si < ei)  {    pi = partition(A, si, ei);    quickSort(A, si, pi - 1);    quickSort(A, pi + 1, ei);  }}
// Java program to remove duplicates, the order of// characters is not maintained in this program import java.util.Arrays; public class GFG{    /* Method to remove duplicates in a sorted array */    static String removeDupsSorted(String str)    {        int res_ind = 1, ip_ind = 1;                 // Character array for removal of duplicate characters        char arr[] = str.toCharArray();                 /* In place removal of duplicate characters*/        while (ip_ind != arr.length)        {            if(arr[ip_ind] != arr[ip_ind-1])            {                arr[res_ind] = arr[ip_ind];                res_ind++;            }            ip_ind++;                   }             str = new String(arr);        return str.substring(0,res_ind);    }          /* Method removes duplicate characters from the string       This function work in-place and fills null characters       in the extra space left */    static String removeDups(String str)    {       // Sort the character array       char temp[] = str.toCharArray();       Arrays.sort(temp);       str = new String(temp);               // Remove duplicates from sorted       return removeDupsSorted(str);    }          // Driver Method    public static void main(String[] args)    {        String str = "geeksforgeeks";        System.out.println(removeDups(str));    }}
# Python3 program to remove duplicates, the order of# characters is not maintained in this program # Utility function to convert string to listdef toMutable(string):    temp = []    for x in string:        temp.append(x)    return temp # Utility function to convert string to listdef toString(List):    return ''.join(List) # Function to remove duplicates in a sorted arraydef removeDupsSorted(List):    res_ind = 1    ip_ind = 1     # In place removal of duplicate characters    while ip_ind != len(List):        if List[ip_ind] != List[ip_ind-1]:            List[res_ind] = List[ip_ind]            res_ind += 1        ip_ind+=1     # After above step string is efgkorskkorss.    # Removing extra kkorss after string    string = toString(List[0:res_ind])     return string # Function removes duplicate characters from the string# This function work in-place and fills null characters# in the extra space leftdef removeDups(string):    # Convert string to list    List = toMutable(string)     # Sort the character list    List.sort()     # Remove duplicates from sorted    return removeDupsSorted(List) # Driver program to test the above functionsstring = "geeksforgeeks"print(removeDups(string)) # This code is contributed by Bhavya Jain
// C# program to remove duplicates, the order of// characters is not maintained in this programusing System;     class GFG{    /* Method to remove duplicates in a sorted array */    static String removeDupsSorted(String str)    {        int res_ind = 1, ip_ind = 1;                 // Character array for removal of duplicate characters        char []arr = str.ToCharArray();                 /* In place removal of duplicate characters*/        while (ip_ind != arr.Length)        {            if(arr[ip_ind] != arr[ip_ind-1])            {                arr[res_ind] = arr[ip_ind];                res_ind++;            }            ip_ind++;                     }             str = new String(arr);        return str.Substring(0,res_ind);    }         /* Method removes duplicate characters from the string    This function work in-place and fills null characters    in the extra space left */    static String removeDups(String str)    {    // Sort the character array    char []temp = str.ToCharArray();    Array.Sort(temp);    str = String.Join("",temp);             // Remove duplicates from sorted    return removeDupsSorted(str);    }         // Driver Method    public static void Main(String[] args)    {        String str = "geeksforgeeks";        Console.WriteLine(removeDups(str));    }} // This code is contributed by 29AjayKumar
<script> function removeDuplicate(string){   return string.split('')    .filter(function(item, pos, self)    {      return self.indexOf(item) == pos;    }   ).join('');} var str = "geeksforgeeks";document.write( " "+removeDuplicate(str)); //This code is contributed by SoumikMondal</script>
Output:  
efgkors
Time Complexity: O(n log n) If we use some nlogn sorting algorithm instead of quicksort.
Auxiliary Space: O(1)
METHOD 4 (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 "the stringing" */
3: Remove extra characters at the end of the resultant string.
  /*  String obtained after this step is "te string" */
Implementation:  
C++
C
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std;# define NO_OF_CHARS 256# define bool int /* Function removes duplicate characters from the stringThis function work in-place and fills null charactersin 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 code */int main(){    char str[] = "geeksforgeeks";    cout << removeDups(str);    return 0;} // This code is contributed by rathbhupendra
# 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;}
// Java program to remove duplicatesimport java.util.*; class RemoveDuplicates{    /* Function removes duplicate characters from the string    This function work in-place */    void removeDuplicates(String str)    {        LinkedHashSet<Character> lhs = new LinkedHashSet<>();        for(int i=0;i<str.length();i++)            lhs.add(str.charAt(i));                 // print string after deleting duplicate elements        for(Character ch : lhs)            System.out.print(ch);    }         /* Driver program to test removeDuplicates */    public static void main(String args[])    {        String str = "geeksforgeeks";        RemoveDuplicates r = new RemoveDuplicates();        r.removeDuplicates(str);    }} // This code has been contributed by Amit Khandelwal (Amit Khandelwal 1)
# Python3 program to remove duplicate characters from an# input stringNO_OF_CHARS = 256 # Since strings in Python are immutable and cannot be changed# This utility function will convert the string to listdef toMutable(string):    List = []    for i in string:        List.append(i)    return List # Utility function that changes list to stringdef toString(List):    return ''.join(List) # Function removes duplicate characters from the string# This function work in-place and fills null characters# in the extra space leftdef removeDups(string):    bin_hash = [0] * NO_OF_CHARS    ip_ind = 0    res_ind = 0    temp = ''    mutableString = toMutable(string)     # In place removal of duplicate characters    while ip_ind != len(mutableString):        temp = mutableString[ip_ind]        if bin_hash[ord(temp)] == 0:            bin_hash[ord(temp)] = 1            mutableString[res_ind] = mutableString[ip_ind]            res_ind+=1        ip_ind+=1      # After above step string is stringiittg.     # Removing extra iittg after string    return toString(mutableString[0:res_ind]) # Driver program to test the above functionsstring = "geeksforgeeks"print(removeDups(string)) # A shorter version for this program is as follows# import collections# print ''.join(collections.OrderedDict.fromkeys(string)) # This code is contributed by Bhavya Jain
// C# program to remove duplicatesusing System;using System.Collections.Generic; class GFG{    /* Function removes duplicate characters    from the string. This function work in-place */    void removeDuplicates(String str)    {        HashSet<char> lhs = new HashSet<char>();        for(int i = 0; i < str.Length; i++)            lhs.Add(str[i]);                 // print string after deleting        // duplicate elements        foreach(char ch in lhs)            Console.Write(ch);    }         // Driver Code    public static void Main(String []args)    {        String str = "geeksforgeeks";        GFG r = new GFG();        r.removeDuplicates(str);    }} // This code is contributed by Rajput-Ji
<script>// javascript program to remove duplicates    /*     * Function removes duplicate characters from the string This function work     * in-place     */    function removeDuplicates( str) {        var lhs = new Set();        for (var i = 0; i < str.length; i++)            lhs.add(str[i]);         // print string after deleting duplicate elements        for (var ch of lhs)            document.write(ch);    }     /* Driver program to test removeDuplicates */             var str = "geeksforgeeks";        removeDuplicates(str); // This code is contributed by umadevi9616</script>
Output:  
geksfor
Time Complexity: O(n)
Auxiliary Space: O(1)
Important Points:  
Method 2 doesn’t maintain the characters as original strings, but method 4 does.
It is assumed that the number of possible characters in the input string is 256. NO_OF_CHARS should be changed accordingly.
calloc() is used instead of malloc() for memory allocations of a counting array (count) to initialize allocated memory to ‘\0’. the malloc() followed by memset() could also be used.
The above algorithm also works for integer array inputs if the range of the integers in the array is given. An example problem is to find the maximum occurring number in an input array given that the input array contains integers only between 1000 to 1100
Method 5 (Using IndexOf() method) : Prerequisite : Java IndexOf() method  
C++
Java
Python3
C#
Javascript
// C++ program to create a unique string#include <bits/stdc++.h>using namespace std; // Function to make the string uniquestring unique(string s){    string str;    int len = s.length();     // loop to traverse the string and    // check for repeating chars using    // IndexOf() method in Java    for(int i = 0; i < len; i++)    {                 // character at i'th index of s        char c = s[i];         // If c is present in str, it returns        // the index of c, else it returns npos        auto found = str.find(c);        if (found == std::string::npos)        {                         // Adding c to str if npos is returned            str += c;        }    }    return str;} // Driver codeint main(){         // Input string with repeating chars    string s = "geeksforgeeks";     cout << unique(s) << endl;} // This code is contributed by nirajgusain5
// Java program to create a unique stringimport java.util.*; class IndexOf {         // Function to make the string unique    public static String unique(String s)    {        String str = new String();        int len = s.length();                 // loop to traverse the string and        // check for repeating chars using        // IndexOf() method in Java        for (int i = 0; i < len; i++)        {            // character at i'th index of s            char c = s.charAt(i);                         // if c is present in str, it returns            // the index of c, else it returns -1            if (str.indexOf(c) < 0)            {                // adding c to str if -1 is returned                str += c;            }        }                 return str;    }     // Driver code    public static void main(String[] args)    {        // Input string with repeating chars        String s = "geeksforgeeks";                 System.out.println(unique(s));    }}
# Python 3 program to create a unique string # Function to make the string unique  def unique(s):     st = ""    length = len(s)     # loop to traverse the string and    # check for repeating chars using    # IndexOf() method in Java    for i in range(length):         # character at i'th index of s        c = s[i]         # if c is present in str, it returns        # the index of c, else it returns - 1        # print(st.index(c))        if c not in st:            # adding c to str if -1 is returned            st += c     return st  # Driver codeif __name__ == "__main__":     # Input string with repeating chars    s = "geeksforgeeks"     print(unique(s))     # This code is contributed by ukasp.
// C# program to create a unique stringusing System;     public class IndexOf{         // Function to make the string unique    public static String unique(String s)    {        String str = "";        int len = s.Length;                 // loop to traverse the string and        // check for repeating chars using        // IndexOf() method in Java        for (int i = 0; i < len; i++)        {            // character at i'th index of s            char c = s[i];                         // if c is present in str, it returns            // the index of c, else it returns -1            if (str.IndexOf(c) < 0)            {                // adding c to str if -1 is returned                str += c;            }        }                 return str;    }     // Driver code    public static void Main(String[] args)    {        // Input string with repeating chars        String s = "geeksforgeeks";                 Console.WriteLine(unique(s));    }} // This code is contributed by Princi Singh
<script>     // JavaScript program to create a unique string         // Function to make the string unique    function unique(s)    {        let str = "";        let len = s.length;                  // loop to traverse the string and        // check for repeating chars using        // IndexOf() method in Java        for (let i = 0; i < len; i++)        {            // character at i'th index of s            let c = s[i];                          // if c is present in str, it returns            // the index of c, else it returns -1            if (str.indexOf(c) < 0)            {                // adding c to str if -1 is returned                str += c;            }        }                  return str;    }           // Input string with repeating chars    let s = "geeksforgeeks";     document.write(unique(s));     </script>
Output:  
geksfor
Thanks debjitdbb for suggesting this approach. 
Method 6 (Using unordered_map STL method) : Prerequisite : unordered_map STL C++ method  
C++
Java
Python3
C#
Javascript
// C++ program to create a unique string using unordered_map /* access time in unordered_map on is O(1) generally if no collisions occurand therefore it helps us check if an element exists in a string in O(1)time complexity with constant space. */ #include <bits/stdc++.h>using namespace std;char* removeDuplicates(char *s,int n){  unordered_map<char,int> exists;  int index = 0;  for(int i=0;i<n;i++){    if(exists[s[i]]==0)    {      s[index++] = s[i];      exists[s[i]]++;    }  }  return s;} //driver codeint main(){  char s[] = "geeksforgeeks";  int n = sizeof(s)/sizeof(s[0]);  cout<<removeDuplicates(s,n)<<endl;  return 0;}
// Java program to create a unique String using unordered_map /* access time in unordered_map on is O(1) generally if no collisions occurand therefore it helps us check if an element exists in a String in O(1)time complexity with constant space. */import java.util.*; class GFG{static char[] removeDuplicates(char []s,int n){  Map<Character,Integer> exists = new HashMap<>();   String st = "";  for(int i = 0; i < n; i++){    if(!exists.containsKey(s[i]))    {      st += s[i];      exists.put(s[i], 1);    }  }  return st.toCharArray();} // driver codepublic static void main(String[] args){  char s[] = "geeksforgeeks".toCharArray();  int n = s.length;  System.out.print(removeDuplicates(s,n));}} // This code is contributed by gauravrajput1
# Python program to create a unique string using unordered_map # access time in unordered_map on is O(1) generally if no collisions occur# and therefore it helps us check if an element exists in a string in O(1)# time complexity with constant space.def removeDuplicates(s, n):    exists = {}    index = 0    ans = ""     for i in range(0, n):        if s[i] not in exists or exists[s[i]] == 0:            s[index] = s[i]            print(s[index], end='')            index += 1            exists[s[i]] = 1 # driver codes = "geeksforgeeks"s1 = list(s)n = len(s1)removeDuplicates(s1, n) # This code is contributed by Palak Gupta
// C# program to create a unique String using unordered_map /* access time in unordered_map on is O(1) generally if no collisions occurand therefore it helps us check if an element exists in a String in O(1)time complexity with constant space. */using System;using System.Collections.Generic; public class GFG{static char[] removeDuplicates(char []s,int n){  Dictionary<char,int> exists = new Dictionary<char, int>();   String st = "";  for(int i = 0; i < n; i++){    if(!exists.ContainsKey(s[i]))    {      st += s[i];      exists.Add(s[i], 1);    }  }  return st.ToCharArray();} // driver codepublic static void Main(String[] args){  char []s = "geeksforgeeks".ToCharArray();  int n = s.Length;  Console.Write(removeDuplicates(s,n));}} // This code is contributed by umadevi9616
<script>// javascript program to create a unique String using unordered_map /* access time in unordered_map on is O(1) generally if no collisions occurand therefore it helps us check if an element exists in a String in O(1)time complexity with constant space. */     function removeDuplicates( s , n) {        var exists = new Map();         var st = "";        for (var i = 0; i < n; i++) {            if (!exists.has(s[i])) {                st += s[i];                exists.set(s[i], 1);            }        }        return st;    }     // driver code             var s = "geeksforgeeks";        var n = s.length;        document.write(removeDuplicates(s, n));// This code contributed by umadevi9616</script>
Output:  
geksfor
Time Complexity : O(n) Auxiliary Space : O(n)Thanks, Allen James Vinoy for suggesting this approach.
METHOD 7 (Simple) 
C++
Java
Python3
C#
Javascript
#include <iostream>using namespace std; int main(){    string s = "abcdabd";    string temp = "";    temp += s.at(0);     for (int i = 1; i < s.length(); i++) {        if (!(temp.find(s.at(i)) < temp.length()))            temp = temp + s.at(i);    }    cout << temp;    return 0;}//This code is contributed by KaaL-EL.
import java.io.*; class GFG {    public static void main(String[] args)    {        String s = "abcdabd";        String temp = "" + s.charAt(0);         for (int i = 1; i < s.length(); i++) {            if (!temp.contains(                    String.valueOf(s.charAt(i))))                temp = temp + s.charAt(i);        }        System.out.println(temp);    }}
# Python code for the above Approachs = "abcdabd"temp = "" + s[0] for i in range(1,len(s)):  if (s[i] not in temp):    temp = temp + s[i] # Printing the Resultprint(temp) # This code is contributed by kothavvsaakash.
using System; public class GFG{   static public void Main (){    string s = "abcdabd";    string temp = "";    temp += s[0];     for (int i = 1; i < s.Length; i++) {      if (temp.IndexOf(s[i]) == -1)        temp = temp + s[i];    }    System.Console.WriteLine(temp);  }} // This code is contributed by akashish__
<script> // JavaScript code for the above Approachlet s = "abcdabd"let temp = "" + s[0] for(let i=1;i<s.length;i++){    if (temp.indexOf(s[i]) == -1)        temp = temp + s[i]} // Printing the Resultdocument.write(temp,"</br>") // This code is contributed by shinjanpatra </script>
abcd
Time Complexity : O(n) 
Auxiliary Space: O(n) 
rathbhupendra
29AjayKumar
princi singh
ALLENJAMESVINOY17BCE0748
Rajput-Ji
princiraj1992
SHUBHAMSINGH10
amirthanand
ukasp
SoumikMondal
todaysgaurav
vaibhavrabadiya3
nirajgusain5
shivanisinghss2110
as5853535
surindertarika1234
GauravRajput1
rajsanghavi9
saunaknandi021000
umadevi9616
adnanirshad158
simranarora5sos
rishavmahato348
prachisoda1234
simmytarika5
raghavendra777
sumitgumber28
surinderdawra388
amartyaghoshgfg
sagar0719kumar
ninja_hattori
harendrakumar123
rajivkumarinfo
kothavvsaakash
shinjanpatra
shivamanandrj9
kaalel
akashish__
frequency-counting
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.