First Non Repeating Character Using Hash in DSA C++ - Time & Space Complexity
We want to find how fast we can identify the first character in a string that appears only once.
How does the time needed grow as the string gets longer?
Analyze the time complexity of the following code snippet.
#include <iostream>
#include <unordered_map>
#include <string>
char firstNonRepeatingChar(const std::string &s) {
std::unordered_map<char, int> freq;
for (char c : s) freq[c]++;
for (char c : s) {
if (freq[c] == 1) return c;
}
return '-';
}
This code counts how many times each character appears, then finds the first one that appears only once.
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 gets longer, the number of steps grows roughly twice as much because we scan the string two times.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 steps (2 x 10) |
| 100 | About 200 steps (2 x 100) |
| 1000 | About 2000 steps (2 x 1000) |
Pattern observation: The steps grow linearly with the input size.
Time Complexity: O(n)
This means the time to find the first non-repeating character grows in direct 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 count and check characters efficiently is a useful skill for many string problems in interviews.
"What if we used a nested loop to check each character against all others? How would the time complexity change?"
Practice
Solution
Step 1: Understand the role of hash map
A hash map stores each character as a key and its frequency as the value, allowing quick frequency lookup.Step 2: Why frequency is important
Knowing frequency helps identify which character appears only once, which is the first non-repeating character.Final Answer:
To store the frequency of each character for quick lookup -> Option DQuick Check:
Hash map = frequency storage [OK]
- Thinking hash map sorts characters
- Using hash map to reverse string
- Confusing hash map with linked list
Solution
Step 1: Identify correct hash map declaration
We need a map with character keys and integer values for frequency, so std::unordered_map is correct.Step 2: Why others are incorrect
std::map freq; reverses key and value types; std::vector<int> freq(26); uses vector, not a hash map; std::unordered_map freq; uses string keys, not char.Final Answer:
std::unordered_map<char, int> freq; -> Option CQuick Check:
Correct map type = unordered_map<char, int> [OK]
- Using map with wrong key-value types
- Using vector instead of map
- Using string keys instead of char
std::string s = "swiss";
std::unordered_map freq;
for (char c : s) freq[c]++;
for (char c : s) {
if (freq[c] == 1) {
std::cout << c << std::endl;
break;
}
}
Solution
Step 1: Count character frequencies
Characters: s(3), w(1), i(1). Frequencies: s=3, w=1, i=1.Step 2: Find first character with frequency 1
Iterate string: 's'(3), 'w'(1) -> first non-repeating is 'w'.Final Answer:
w -> Option BQuick Check:
First unique char = w [OK]
- Printing first character without checking frequency
- Confusing 'i' as first unique
- Ignoring frequency counts
std::string s = "hello";
std::unordered_map freq;
for (int i = 0; i <= s.size(); i++) {
freq[s[i]]++;
}
for (int i = 0; i < s.size(); i++) {
if (freq[s[i]] == 1) {
std::cout << s[i] << std::endl;
break;
}
}
Solution
Step 1: Check loop boundary in frequency count
The loop uses i <= s.size(), which accesses s[s.size()] out of bounds causing undefined behavior.Step 2: Correct loop boundary
Change condition to i < s.size() to avoid out-of-range access.Final Answer:
Loop condition should be i < s.size(), not i <= s.size() -> Option AQuick Check:
Loop boundary off by one error [OK]
- Using <= instead of < in loops
- Confusing char and string keys
- Thinking break is missing
"aabbccdde", which modification to the standard hash map approach will correctly find the first non-repeating character when some characters appear multiple times and others only once at the end?Solution
Step 1: Understand problem with standard hash map
Hash map stores frequencies but does not keep order, so first unique character position is lost.Step 2: Use queue to track order
By storing characters in a queue as they appear, and checking frequency, we can find the first non-repeating character in order.Final Answer:
Store character frequencies and track insertion order using a queue -> Option AQuick Check:
Frequency + order tracking = correct first unique [OK]
- Sorting string loses original order
- Using vector loses quick lookup
- Stopping count too early
Ready to prove it?
Pass the test and this pattern moves unknown
