Remove duplicate characters
Remove repeated characters from a string while preserving the first occurrence of each character.
Course progress
Problem 59 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
text = "banana"
Expected output
ban
What is happening?
Keep the first b, a, and n. Every later a or n has already appeared, so those characters are skipped.
Solution strategy
Build the right mental model
Add each character to a set and append it to the result only when the set reports that it was not already present.
Core concepts
strings · hash set
Complexity
Average time O(n), space O(k), where k is the number of distinct characters.
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for remove-duplicate-characters
using System;
using System.Collections.Generic;
using System.Text;
class Program
{
static string RemoveDuplicates(string text)
{
var seen = new HashSet<char>();
var result = new StringBuilder();
foreach (char symbol in text)
if (seen.Add(symbol)) result.Append(symbol);
return result.ToString();
}
static void Main()
{
Console.WriteLine(RemoveDuplicates("banana"));
}
}Knowledge check
Questions students often ask
What is the main idea behind remove duplicate characters?
Add each character to a set and append it to the result only when the set reports that it was not already present.
What is the time and space complexity of this solution?
Average time O(n), space O(k), where k is the number of distinct characters.
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.