Remove duplicates from a given string

Given a string S which may contain lowercase and uppercase characters. The task is to remove all duplicate characters from the string and find the resultant string.

Note: The order of remaining characters in the output should be the same as in the original string.

Example:

Input: Str = w3wiki
Output: geksfor
Explanation: After removing duplicate characters such as e, k, g, s, we have string as “geksfor”.

Input: Str = HappyNewYear
Output: HapyNewYr
Explanation: After removing duplicate characters such as p, e, a, we have string as “HapyNewYr”.

Naive Approach:

Iterate through the string and for each character check if that particular character has occurred before it in the string. If not, add the character to the result, otherwise the character is not added to result.

Below is the implementation of above approach:

C++
// 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 code
int main()
{
   char str[]= "w3wiki";
   int n = sizeof(str) / sizeof(str[0]);
   cout << removeDuplicate(str, n);
   return 0;
}
C
#include <stdio.h>
#include <string.h>

char* removeDuplicate(char str[], int n)
{
    // Used as an 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 the result.
        if (j == i)
            str[index++] = str[i];
    }

    // Add null character at the end to terminate the string
    str[index] = '\0';

    return str;
}

// Driver code
int main()
{
    char str[] = "w3wiki";
    int n = sizeof(str) / sizeof(str[0]);
    printf("%s\n", removeDuplicate(str, n));
    return 0;
}
Java
// Java program to remove duplicate character
// from character array and print in sorted
// order
import 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[] = "w3wiki".toCharArray();
        int n = str.length;
        System.out.println(removeDuplicate(str, n));
    }
}

// This code is contributed by Rajput-Ji
Python
string="w3wiki"
p=""
for char in string:
    if char not in p:
        p=p+char
print(p)
k=list("w3wiki")
C#
// C# program to remove duplicate character
// from character array and print in sorted
// order
using 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 code
public static void Main(String[] args)
{
    char []str = "w3wiki".ToCharArray();
    int n = str.Length;
    Console.WriteLine(removeDuplicate(str, n));
}
}

// This code is contributed by PrinciRaj1992 
Javascript
<script>

// JavaScript program to remove duplicate character
// from character array and print in sorted
// order
function 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 = "w3wiki".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 the order of elements the same as the input. 

Remove duplicates from a given string using Hashing

Iterating through the given string and use a map to efficiently track of encountered characters. If a character is encountered for the first time, it’s added to the result string, Otherwise, it’s skipped. This ensures the output string contains only unique characters in the same order as the input string.

Below is the implementation of above approach:

C++
// C++ 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. */

#include <bits/stdc++.h>
using namespace std;
string removeDuplicates(string s, int n)
{
    unordered_map<char, int> exists;
    string ans = "";
    for (int i = 0; i < n; i++) {
        if (exists.find(s[i]) == exists.end()) {
            ans.push_back(s[i]);
            exists[s[i]]++;
        }
    }
    return ans;
}

// driver code
int main()
{
    string s = "w3wiki";
    int n = s.size();
    cout << removeDuplicates(s, n) << endl;
    return 0;
}
Java
// Java 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. */
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 code
public static void main(String[] args){
  char s[] = "w3wiki".toCharArray();
  int n = s.length;
  System.out.print(removeDuplicates(s,n));
}
}
Python
# 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 code
s = "w3wiki"
s1 = list(s)
n = len(s1)
removeDuplicates(s1, n)
C#
// C# 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. */
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 code
public static void Main(String[] args){
  char []s = "w3wiki".ToCharArray();
  int n = s.Length;
  Console.Write(removeDuplicates(s,n));
}
}
Javascript
<script>
// javascript 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. */
     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 = "w3wiki";
        var n = s.length;
        document.write(removeDuplicates(s, n));

</script>

Output
geksfor

Time Complexity: O(n)
Auxiliary Space: O(n)

Remove duplicates from a given string using char frequency Array

Iterating through the given string and use a character array initilize with 0 frequency to efficiently track of encountered characters. If current character’s frequency is 0, then it’s added to the result string and increment frequency by 1, Otherwise, it’s skipped. This ensures the output string contains only unique characters in the same order as the input string.

Below is the implementation of above approach:

C++
// C++ program to create a unique string using frequency
// array
#include <bits/stdc++.h>
using namespace std;

// Function to remove duplicate characters
string removeDuplicates(string s, int n)
{
    // Create an integer array to store all characters
    // frequency make its size 255 as per ASCII values
    vector<int> ch(255, 0);

    // Create result string
    string ans = "";

    for (int i = 0; i < n; i++) {
        // Check if current character's frequency is 0 or
        // not
        if (ch[s[i]] == 0) {

            // Add char if frequency is 0
            ans.push_back(s[i]);

            // Increment frequency by 1
            ch[s[i]]++;
        }
    }
    return ans;
}

// driver code
int main()
{
    string s = "w3wiki";
    int n = s.size();
    cout << removeDuplicates(s, n) << endl;
    return 0;
}

// This code is contributed by Susobhan Akhuli

Output
geksfor

Time Complexity: O(n)
Auxiliary Space: O(1)



Contact Us