Remove Duplicate Characters from a String

Problem

Remove duplicate characters from a string, keeping only the first occurrence of each, in original order.

Input:  s = "programming"
Output: "progamin"

Python Solution

def remove_duplicate_chars(s):
    seen = set()
    result = []
    for ch in s:
        if ch not in seen:
            seen.add(ch)
            result.append(ch)
    return "".join(result)

C++ Solution

string removeDuplicateChars(string s) {
    unordered_set<char> seen;
    string result;
    for (char ch : s) {
        if (seen.find(ch) == seen.end()) {
            seen.insert(ch);
            result += ch;
        }
    }
    return result;
}

Java Solution

class Solution {
    public String removeDuplicateChars(String s) {
        Set<Character> seen = new LinkedHashSet<>();
        for (char ch : s.toCharArray()) {
            seen.add(ch);
        }
        StringBuilder result = new StringBuilder();
        for (char ch : seen) result.append(ch);
        return result.toString();
    }
}

Complexity

Time: O(n) — one pass, with O(1) average set membership checks. Space: O(k) — where k is the number of distinct characters kept.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.