Interview question
Find the first non-repeating character
Implements a stable first-unique-character search using counts and original order.
TL;DR
Implements a stable first-unique-character search using counts and original order.
Dictionary counting, order preservation, null handling, and clear edge-case reasoning.
Practice the problem like a real interview: restate, reason, implement, and test.
Implement FirstUniqueChar(string text) returning char?. The search is case-sensitive. Return null when no character appears exactly once.
Input: "swiss"
Output: 'w'
Input: "aabb"
Output: null
I would make two passes. The first pass counts every character. The second pass walks the original string and returns the first character whose count is one. That keeps the code simple and avoids tricky state. If memory were constrained or the character set were fixed, I could discuss arrays, but a dictionary is the clean general solution.
public static char? FirstUniqueChar(string? text)
{
if (string.IsNullOrEmpty(text))
{
return null;
}
var counts = new Dictionary<char, int>();
foreach (var ch in text)
{
counts[ch] = counts.TryGetValue(ch, out var count) ? count + 1 : 1;
}
foreach (var ch in text)
{
if (counts[ch] == 1)
{
return ch;
}
}
return null;
}
Time is O(n) for two linear passes. Space is O(k), where k is the number of distinct characters.
aA.Next in Coding Practice: Group Orders