C# Program to Find First Non Repeating Character
Dictionary<char,int> to count characters, then loop through the string to find the first character with count 1; for example, foreach (var ch in input) if (counts[ch] == 1) return ch;.Examples
How to Think About It
Algorithm
Code
using System; using System.Collections.Generic; class Program { static void Main() { string input = "swiss"; char result = FirstNonRepeatingChar(input); Console.WriteLine(result == '\0' ? "No non-repeating character found" : result.ToString()); } static char FirstNonRepeatingChar(string s) { var counts = new Dictionary<char, int>(); foreach (var ch in s) { counts[ch] = counts.GetValueOrDefault(ch, 0) + 1; } foreach (var ch in s) { if (counts[ch] == 1) return ch; } return '\0'; } }
Dry Run
Let's trace the input "swiss" through the code to find the first non repeating character.
Count characters
s:3, w:1, i:1
Find first with count 1
Check 's' (3), 'w' (1) → found 'w'
| Character | Count |
|---|---|
| s | 3 |
| w | 1 |
| i | 1 |
Why This Works
Step 1: Counting characters
We use a dictionary to count how many times each character appears in the string with counts[ch] = counts.GetValueOrDefault(ch, 0) + 1.
Step 2: Finding the first unique character
We loop through the string again and check the count for each character. The first character with count 1 is returned.
Step 3: Return result or fallback
If no character has count 1, we return '\0' and print a message saying no non-repeating character was found.
Alternative Approaches
using System; using System.Linq; class Program { static void Main() { string input = "swiss"; var result = input.GroupBy(c => c) .Where(g => g.Count() == 1) .Select(g => g.Key) .FirstOrDefault(); Console.WriteLine(result == '\0' ? "No non-repeating character found" : result.ToString()); } }
using System; class Program { static void Main() { string input = "swiss"; char result = FirstNonRepeatingChar(input); Console.WriteLine(result == '\0' ? "No non-repeating character found" : result.ToString()); } static char FirstNonRepeatingChar(string s) { int[] counts = new int[256]; foreach (var ch in s) counts[ch]++; foreach (var ch in s) if (counts[ch] == 1) return ch; return '\0'; } }
Complexity: O(n) time, O(n) space
Time Complexity
The program loops through the string twice: once to count characters and once to find the first unique character, so it runs in linear time O(n).
Space Complexity
It uses extra space for the dictionary to store counts, which can be up to O(n) in the worst case if all characters are unique.
Which Approach is Fastest?
Using an array for ASCII characters is fastest due to direct indexing, but dictionary-based or LINQ approaches are more flexible for Unicode.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Dictionary Counting | O(n) | O(n) | Unicode strings, general use |
| LINQ Grouping | O(n) | O(n) | Concise code, small strings |
| Array Counting (ASCII) | O(n) | O(1) | ASCII strings, performance critical |