easyString ProblemsJava

Remove All Duplicate Characters From a String

Produce a string that keeps only the first occurrence of each character.

Quick Answer

Add each character to a LinkedHashSet, which ignores repeats but keeps first-appearance order. Then build a string from the set. The result contains each character exactly once, in the order it first appeared. This runs in O(n) time.

Problem Statement

Given a string, remove every duplicate character so that each character appears only once. Keep the first occurrence of each character and drop all later repeats, preserving the original left-to-right order.

For example, programming becomes progamin — the second r, the second m and the final g are removed.

Input: A single string s.

Output: A string with each character kept only on its first appearance.

Examples

Example 1
Input:  "programming"
Output: progamin

Repeated r, m and g after their first appearance are removed.

Example 2
Input:  "aabbcc"
Output: abc

Each of a, b and c is kept once, in first-appearance order.

Constraints

  • 0 <= s.length <= 10^5
  • Preserve the order of first appearances

Think Before You Code

Reveal the questions to ask yourself first
  • How do you know whether a character has already been kept?
  • What structure both removes duplicates and preserves order?
  • How do you assemble the surviving characters back into a string?
  • Should the comparison be case-sensitive?

Hints

Open them one at a time — try after each before revealing the next.

Hint 1
Track which characters you have already emitted so you can skip repeats.
Hint 2
A LinkedHashSet stores each element once and keeps insertion order — exactly what this needs.
Hint 3
Add every character to the set, then walk the set to build the deduplicated string.

Approach

Reveal the step-by-step approach

Let an ordered set do the deduplication.

  1. Create a LinkedHashSet<Character>.
  2. Add every character of the string to the set. Duplicates are ignored, and the set remembers the order each character was first inserted.
  3. Iterate the set and append each character to a StringBuilder.
  4. Return the built string.

Because the set rejects repeats and keeps insertion order, the output naturally contains each character once in first-appearance order.

Dry Run

Walk through the example step by step

Deduplicating "programming":

char | set after add
-----+---------------------------
p    | [p]
r    | [p, r]
o    | [p, r, o]
g    | [p, r, o, g]
r    | [p, r, o, g]        (duplicate ignored)
a    | [p, r, o, g, a]
m    | [p, r, o, g, a, m]
m    | [p, r, o, g, a, m]  (duplicate ignored)
i    | [p, r, o, g, a, m, i]
n    | [p, r, o, g, a, m, i, n]
g    | [p, r, o, g, a, m, i, n]  (duplicate ignored)
build -> "progamin"

Solution

Reveal the full Java solution
import java.util.LinkedHashSet;
import java.util.Set;

public class RemoveDuplicateChars {
    public static String removeDuplicates(String s) {
        Set<Character> seen = new LinkedHashSet<>();
        for (int i = 0; i < s.length(); i++) {
            seen.add(s.charAt(i));
        }
        StringBuilder sb = new StringBuilder();
        for (char c : seen) {
            sb.append(c);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(removeDuplicates("programming")); // progamin
        System.out.println(removeDuplicates("aabbcc"));      // abc
    }
}

A LinkedHashSet accepts a character only if it is not already present, so the second and later copies are silently dropped. Its insertion-order guarantee means iterating the set yields characters in the order they first appeared. Building the result with a StringBuilder avoids creating a new string on every append.

Time: O(n) where n is the string lengthSpace: O(k) where k is the number of distinct characters

Common Mistakes

  • Using a plain HashSet, which drops duplicates but scrambles the order.
  • Keeping the last occurrence instead of the first by rebuilding the set backward.
  • Comparing characters case-insensitively when the problem expects exact matches.

Edge Cases to Test

  • An empty string returns an empty string.
  • A string with no duplicates is returned unchanged.
  • A string of one repeated character, like "aaaa", collapses to "a".

Interview Follow-Ups

  • How would you keep the last occurrence of each character instead of the first?
  • How would you remove duplicates in place using an int[256] seen array?
  • How would you make the deduplication case-insensitive?

Practising for Java interviews?

CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Explore the Java Full Stack program →
Chat with us