Remove duplicates from a string

Last Updated : 4 Jul, 2026

Given a string s which may contain lowercase and uppercase characters. Remove all the 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: "geEksforG"
Explanation: After removing duplicate characters such as E, e, k, s, we have string as "geEksforG".

Input: s = "HaPpyNewYear"
Output: "HaPpyNewYr"
Explanation: After removing duplicate characters such as e, a, we have string as "HaPpyNewYr".

Try It Yourself
redirect icon

[Naive Approach] Check Previous Occurrence of Every Character - O(n^2) Time O(1) Space

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.

C++
#include <iostream>
#include <string>
using namespace std;

string removeDuplicates(string &s)
{
    int index = 0;

    // Traverse through all characters
    for (int i = 0; i < s.size(); i++)
    {
        int j;
        // Check if s[i] is present before it
        for (j = 0; j < i; j++)
        {
            if (s[i] == s[j])
                break;
        }

        // If not present, add it to result
        if (j == i)
            s[index++] = s[i];
    }

    // Resize string to remove extra characters
    s.resize(index);

    return s;
}
// Driver code
int main()
{
    string s = "geEksforGEeks";
    cout << removeDuplicates(s);
    return 0;
}
C
#include <stdio.h>
#include <string.h>

char* removeDuplicates(char* s)
{
    int index = 0;

    // Traverse through all characters
    for (int i = 0; i < strlen(s); i++)
    {
        int j;
        // Check if s[i] is present before it
        for (j = 0; j < i; j++)
        {
            if (s[i] == s[j])
                break;
        }

        // If not present, add it to result
        if (j == i)
            s[index++] = s[i];
    }

    s[index] = '\0';

    return s;
}

int main()
{
    char s[] = "geEksforGEeks";
    printf("%s", removeDuplicates(s));
    return 0;
}
Java
public class GFG {
    public static String removeDuplicates(String s) {
        int index = 0;
        char[] charArray = s.toCharArray();

        // Traverse through all characters
        for (int i = 0; i < s.length(); i++) {
            int j;
            // Check if s[i] is present before it
            for (j = 0; j < i; j++) {
                if (s.charAt(i) == s.charAt(j))
                    break;
            }

            // If not present, add it to result
            if (j == i)
                charArray[index++] = s.charAt(i);
        }

        return new String(charArray, 0, index);
    }

    public static void main(String[] args) {
        String s = "geEksforGEeks";
        System.out.println(removeDuplicates(s));
    }
}
Python
def removeDuplicates(s):
    index = 0
    s = list(s)

    # Traverse through all characters
    for i in range(len(s)):
        j = 0
        
        # Check if s[i] is present before it
        while j < i:
            if s[i] == s[j]:
                break
            j += 1

        # If not present, add it to result
        if j == i:
            s[index] = s[i]
            index += 1

    return ''.join(s[:index])


# Driver code
s = "geEksforGEeks"
print(removeDuplicates(s))
C#
using System;

public class GFG
{
    public static string removeDuplicates(string s)
    {
        int index = 0;
        char[] charArray = s.ToCharArray();

        // Traverse through all characters
        for (int i = 0; i < s.Length; i++)
        {
            int j;
            // Check if s[i] is present before it
            for (j = 0; j < i; j++)
            {
                if (s[i] == s[j])
                    break;
            }

            // If not present, add it to result
            if (j == i)
                charArray[index++] = s[i];
        }

        return new string(charArray, 0, index);
    }

    public static void Main()
    {
        string s = "geEksforGEeks";
        Console.WriteLine(removeDuplicates(s));
    }
}
JavaScript
function removeDuplicates(s) {
    let index = 0;

    // Traverse through all characters
    for (let i = 0; i < s.length; i++) {
        let j;
        // Check if s[i] is present before it
        for (j = 0; j < i; j++) {
            if (s[i] === s[j])
                break;
        }

        // If not present, add it to result
        if (j === i)
            s = s.substring(0, index) + s[i] + s.substring(index + 1);
            index++;
    }

    return s.substring(0, index);
}

// Driver code
let s = "geEksforGEeks";
console.log(removeDuplicates(s));

Output
geEksforG

[Expected Approach] Using Hash Set - O(n) Time O(1) Space

The Idea is to Use a hash set to track seen characters while traversing the string. If a character is not in the set, add it to the result; otherwise, skip it. This removes duplicates while preserving order.

Algorithm:

  • Create an empty hash set to store visited characters.
  • Initialize an empty string ans to store the result.
  • Traverse the input string character by character.
  • For each character, check if it is present in the set.
  • If not present, append it to ans and insert it into the set.
  • Otherwise, skip the character.
  • Return the final string ans containing unique characters.
C++
#include <iostream>
#include <unordered_set>
#include <string>
using namespace std;

// Function to remove duplicate characters
// User function template for C++
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
        if (exists.find(c) == exists.end())
        {
            ans.push_back(c);
            exists.insert(c);
        }
    }

    return ans;
}

int main()
{
    string s = "geEksforGEeks";
    cout << removeDuplicates(s) << endl;
    return 0;
}
Java
import java.util.HashSet;

// Function to remove duplicate characters
// User function template for Java
public class GfG {
    public static String removeDuplicates(String s) {
        HashSet<Character> exists = new HashSet<>();
        StringBuilder ans = new StringBuilder();

        // Traverse through the string
        for (char c : s.toCharArray()) {
            // If character is not found in set, add it
            if (!exists.contains(c)) {
                ans.append(c);
                exists.add(c);
            }
        }

        return ans.toString();
    }

    public static void main(String[] args) {
        String s = "geEksforGEeks";
        System.out.println(removeDuplicates(s));
    }
}
Python
# Function to remove duplicate characters
# User function template for Python
def removeDuplicates(s):

    exists = set()
    ans = ""

    # Traverse through the string
    for c in s:

        # If character is not found in set, add it
        if c not in exists:
            ans += c
            exists.add(c)

    return ans

if __name__ == "__main__":
    s = "geEksforGEeks"
    print(removeDuplicates(s))
C#
using System;
using System.Collections.Generic;

// Function to remove duplicate characters
// User function template for C#
public class GFG
{
    public static string removeDuplicates(string s)
    {
        HashSet<char> exists = new HashSet<char>();
        string ans = "";

        // Traverse through the string
        foreach (char c in s)
        {
            // If character is not found in set, add it
            if (!exists.Contains(c))
            {
                ans += c;
                exists.Add(c);
            }
        }

        return ans;
    }

    public static void Main()
    {
        string s = "geEksforGEeks";
        Console.WriteLine(removeDuplicates(s));
    }
}
JavaScript
// Function to remove duplicate characters
// User function template for JavaScript
function removeDuplicates(s) {
    let exists = new Set();
    let ans = '';

    // Traverse through the string
    for (let c of s) {
        // If character is not found in set, add it
        if (!exists.has(c)) {
            ans += c;
            exists.add(c);
        }
    }

    return ans;
}

// Driver code
let s = 'geEksforGEeks';
console.log(removeDuplicates(s));

Output
geEksforG

[Alternate Approach] Using Frequency Array - O(n) Time O(1) Space

The idea is to use a frequency array to track visited characters. While traversing the string, add a character to the result only if its frequency is 0, otherwise skip it. This keeps characters unique and preserves order.

Algorithm:

  • Create a frequency array of size 256 initialized with 0.
  • Initialize an empty string ans to store the result.
  • Traverse the input string character by character.
  • For each character, check its frequency in the array.
  • If the frequency is 0, append it to ans and mark it as visited by setting it to 1.
  • Otherwise, skip the character.
  • Return the final string ans containing unique characters.
C++
#include <iostream>
#include <string>
using namespace std;


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;
}

int main()
{
    string s = "geEksforGEeks";
    cout << removeDuplicates(s) << endl;
    return 0;
}
C
#include <stdio.h>
#include <string.h>

char* removeDuplicates(char* s) {
  
    // Create an integer array to store 
    // frequency for ASCII characters
    int ch[256] = { 0 };
    int index = 0;
    int length = strlen(s);

    // Traverse the input string
    for (int i = 0; i < length; i++) {
        char c = s[i];

        // Check if current character's frequency is 0
        if (ch[(unsigned char)c] == 0) {
            
            // Add char if frequency is 0
            s[index++] = c;

            // Increment frequency
            ch[(unsigned char)c]++;
        }
    }
    s[index] = '\0';  // Null-terminate the result string
    return s;
}

int main() {
    char s[] = "geEksforGEeks";
    printf("%s\n", removeDuplicates(s));
    return 0;
}
Java
import java.util.Arrays;

public class GFG {
    public static String removeDuplicates(String s) {
      
        // Create an integer array to store 
        // frequency for ASCII characters
        int[] ch = new int[256];
        StringBuilder ans = new StringBuilder();

        // Traverse the input string
        for (char c : s.toCharArray()) {

            // Check if current character's frequency is 0
            if (ch[c] == 0) {
                
                // Add char if frequency is 0
                ans.append(c);

                // Increment frequency
                ch[c]++;
            }
        }
        return ans.toString();
    }

    public static void main(String[] args) {
        String s = "geEksforGEeks";
        System.out.println(removeDuplicates(s));
    }
}
Python
def removeDuplicates(s):
  
    # Function to remove duplicate characters
    # Create a list to store frequency for ASCII characters
    ch = [0] * 256
    result = []

    # Traverse the input string
    for char in s:
        
        # Check if current character's frequency is 0
        if ch[ord(char)] == 0:
            
            # Add char if frequency is 0
            result.append(char)

            # Increment frequency
            ch[ord(char)] += 1
    
    return ''.join(result)

if __name__ == "__main__":
    s = "geEksforGEeks"
    print(removeDuplicates(s))
C#
using System;

public class GFG {
    public static string removeDuplicates(string s) {
      
        // Create an integer array to store 
        // frequency for ASCII characters
        int[] ch = new int[256];
        System.Text.StringBuilder ans = new System.Text.StringBuilder();

        // Traverse the input string
        foreach (char c in s) {

            // Check if current character's frequency is 0
            if (ch[c] == 0) {
                
                // Add char if frequency is 0
                ans.Append(c);

                // Increment frequency
                ch[c]++;
            }
        }
        return ans.ToString();
    }

    public static void Main() {
        string s = "geEksforGEeks";
        Console.WriteLine(removeDuplicates(s));
    }
}
JavaScript
function removeDuplicates(s) {

    // Function to remove duplicate characters
    // Create an integer array to store 
    // frequency for ASCII characters
    let ch = new Array(256).fill(0);
    let result = '';

    // Traverse the input string
    for (let char of s) {
        
        // Check if current character's frequency is 0
        if (ch[char.charCodeAt(0)] === 0) {
            
            // Add char if frequency is 0
            result += char;

            // Increment frequency
            ch[char.charCodeAt(0)]++;
        }
    }
    
    return result;
}

// Driver code
let s = "geEksforGEeks";
console.log(removeDuplicates(s));

Output
geEksforG
Comment