First Non Repeating Character Using Hash in DSA C# - Time & Space Complexity
We want to know how long it takes to find the first character that appears only once in a string using a hash map.
How does the time needed grow as the string gets longer?
Analyze the time complexity of the following code snippet.
public char FirstNonRepeatingChar(string s) {
var counts = new Dictionary<char, int>();
foreach (var c in s) {
counts[c] = counts.TryGetValue(c, out var cnt) ? cnt + 1 : 1;
}
foreach (var c in s) {
if (counts[c] == 1) return c;
}
return '\0';
}
This code counts how many times each character appears, then finds the first character with count one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Two loops over the string characters.
- How many times: Each loop runs once over all characters, so twice in total.
As the string length grows, the number of operations grows roughly twice as fast because of two passes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 operations |
| 100 | About 200 operations |
| 1000 | About 2000 operations |
Pattern observation: Operations grow linearly with input size.
Time Complexity: O(n)
This means the time to find the first non-repeating character grows directly in proportion to the string length.
[X] Wrong: "Because there are two loops, the time complexity is O(n²)."
[OK] Correct: The loops run one after another, not nested, so their times add up, not multiply.
Understanding how to analyze simple loops and hash map usage helps you explain efficient solutions clearly in interviews.
"What if we used a nested loop to check each character against all others instead of a hash map? How would the time complexity change?"
Practice
Solution
Step 1: Understand the role of hash in frequency counting
A hash (dictionary) stores each character as a key and counts how many times it appears in the string.Step 2: Use frequency to find non-repeating character
By checking the counts, we can find the first character with count 1, which is the first non-repeating character.Final Answer:
To count the frequency of each character in the string -> Option AQuick Check:
Hash = frequency map [OK]
- Trying to sort characters instead of counting
- Using hash to store indexes only
- Ignoring character frequency
input?Solution
Step 1: Check dictionary key and value types
We need a dictionary withcharkeys andintvalues to count frequencies.Step 2: Verify frequency counting logic
var freq = new Dictionary(); foreach (char c in input) { if (freq.ContainsKey(c)) freq[c]++; else freq[c] = 1; } correctly checks if the character exists and increments count or sets it to 1.Final Answer:
var freq = new Dictionary(); foreach (char c in input) { if (freq.ContainsKey(c)) freq[c]++; else freq[c] = 1; } -> Option AQuick Check:
Correct dictionary type and counting logic [OK]
- Using wrong dictionary types
- Not incrementing counts correctly
- Using List instead of Dictionary
string input = "swiss";
var freq = new Dictionary();
foreach (char c in input) {
if (freq.ContainsKey(c)) freq[c]++;
else freq[c] = 1;
}
char result = '\0';
foreach (char c in input) {
if (freq[c] == 1) {
result = c;
break;
}
}
Console.WriteLine(result == '\0' ? "None" : result);Solution
Step 1: Count character frequencies in "swiss"
s appears 3 times, w appears 1 time, i appears 1 time.Step 2: Find first character with frequency 1 in original order
Order is s, w, i, s, s. The first with count 1 is 'w'.Final Answer:
w -> Option CQuick Check:
First unique char = w [OK]
- Choosing 'i' because it is unique but not first
- Choosing 's' which repeats
- Printing None incorrectly
string input = "hello";
var freq = new Dictionary();
foreach (char c in input) {
freq[c] = freq[c] + 1;
}
char result = '\0';
foreach (char c in input) {
if (freq[c] == 1) {
result = c;
break;
}
}
Console.WriteLine(result == '\0' ? "None" : result);Solution
Step 1: Analyze frequency counting loop
The code tries to increment freq[c] without checking if c exists in dictionary, causing error.Step 2: Identify correct fix
Must check if freq contains c before incrementing or initialize freq[c] to 1 if missing.Final Answer:
freq[c] is used before initialization causing KeyNotFoundException -> Option BQuick Check:
Accessing uninitialized key causes error [OK]
- Assuming dictionary auto-initializes keys
- Ignoring exception details
- Missing initialization logic
input = "aabbccddeeffg", which character will be the first non-repeating character using a hash-based approach? If none exists, return 'None'.Solution
Step 1: Count frequencies of each character
Characters a,b,c,d,e,f appear twice each; g appears once.Step 2: Find first character with frequency 1 in string order
String order is a,a,b,b,c,c,d,d,e,e,f,f,g. The first with count 1 is 'g'.Final Answer:
g -> Option DQuick Check:
Only 'g' is unique and first non-repeating [OK]
- Choosing 'None' incorrectly
- Picking repeated characters
- Ignoring last unique character
Ready to prove it?
Pass the test and this pattern moves unknown
