Open In App

Remove duplicates from a string

Last Updated : 11 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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: s = geeksforgeeks
Output: geksfor
Explanation: After removing duplicate characters such as e, k, g, s, we have string as “geksfor”.

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

Naive Approach – O(n^2) Time

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++
#include <bits/stdc++.h>
using namespace std;

string removeDuplicate(string s)
{
   // Used as index in the modified string
   int index = 0;   

   // Traverse through all characters
   for (int i = 0; i < s.size(); i++) {
       
     // Check if s[i] is present before it  
     int j;  
     for (j = 0; j < i; j++) 
        if (s[i] == s[j])
           break;
     
     // If not present, then add it to result
     if (j == i)
        s[index++] = s[i];
   }
   
   // Resize the string to remove extra characters
   s.resize(index);
   
   return s;
}

// Driver code
int main()
{
   string s = "geeksforgeeks";
   cout << removeDuplicate(s);
   return 0;
}
C Java Python C# JavaScript

Output
geksfor

Time Complexity: O(n * n) 
Auxiliary Space: O(1), Keeps the order of elements the same as the input. 

Using Hash Set – O(n) Time

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++
#include <bits/stdc++.h>
using namespace std;

// Function to remove duplicate characters
// using unordered_set
string removeDuplicates(string &s)
{
    unordered_set<char> exists; 
    string ans = "";

    // Traverse through the string
    for (char c : s) {
      
        // If character is not found in set, 
        // add it to result
        if (exists.find(c) == exists.end()) {
            ans.push_back(c);
            exists.insert(c); 
        }
    }
    
    return ans;
}

// Driver code
int main()
{
    string s = "geeksforgeeks";
    cout << removeDuplicates(s) << endl;
    return 0;
}
C Java Python C# JavaScript

Output
geksfor

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

Using Frequency Array – O(n)

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++
#include <bits/stdc++.h>
using namespace std;

// Function to remove duplicate characters
string removeDuplicates(string &s)
{
    // Create an integer array to store 
    // frequency for ASCII characters
    vector<int> ch(256, 0);

    // Create result string
    string ans = "";

    // Traverse the input string
    for (char c : s) {
      
        // Check if current character's frequency is 0
        if (ch[c] == 0) {
          
            // Add char if frequency is 0
            ans.push_back(c);

            // Increment frequency
            ch[c]++;
        }
    }
    return ans;
}

// Driver code
int main()
{
    string s = "geeksforgeeks";
    cout << removeDuplicates(s) << endl;
    return 0;
}
C Java Python C# JavaScript

Output
geksfor

Time Complexity: O(n)
Auxiliary Space: O(1) considering that the alphabet size is constant.



Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg