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)



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. 

Similar Reads

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....

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....