First non-repeating character
Return the first character that occurs exactly once in a string, or an empty string when every character repeats.
Course progress
Problem 39 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 = "swiss"
Expected output
w
What is happening?
The letters s and i repeat, while w appears once. Because w is the first character with frequency one, it is returned.
Solution strategy
Build the right mental model
Count every character in one pass, then scan the original order again and return the first character whose count is one.
Core concepts
dictionary · strings
Complexity
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 first-non-repeating-character
using System;
using System.Collections.Generic;
class Program
{
static string FirstUnique(string text)
{
var counts = new Dictionary<char, int>();
foreach (char symbol in text)
{
int count;
counts.TryGetValue(symbol, out count);
counts[symbol] = count + 1;
}
foreach (char symbol in text)
if (counts[symbol] == 1) return symbol.ToString();
return "";
}
static void Main()
{
Console.WriteLine(FirstUnique("swiss"));
}
}Knowledge check
Questions students often ask
What is the main idea behind first non-repeating character?
Count every character in one pass, then scan the original order again and return the first character whose count is one.
What is the time and space complexity of this solution?
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.