First Non Repeating Character Using Hash in DSA Java - Time & Space Complexity
We want to find 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.
import java.util.HashMap;
public class Solution {
public static char firstNonRepeatingChar(String s) {
HashMap countMap = new HashMap<>();
for (char c : s.toCharArray()) {
countMap.put(c, countMap.getOrDefault(c, 0) + 1);
}
for (char c : s.toCharArray()) {
if (countMap.get(c) == 1) return c;
}
return '_';
}
}
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 code goes through all characters twice.
| 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 operations grow roughly twice the input size, which means it grows linearly.
Time Complexity: O(n)
This means the time to find the first non-repeating character grows directly with the length of the string.
[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 this linear time approach shows you can use simple data structures like hash maps to solve problems efficiently, a skill valued in many coding challenges.
"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 problem goal
The algorithm aims to find the first character in the string that does not repeat anywhere else.Step 2: Role of hash map
A hash map stores character counts to quickly check which characters appear once.Final Answer:
Finds the first character in a string that appears only once -> Option DQuick Check:
First non repeating character = Finds the first character in a string that appears only once [OK]
- Thinking it counts total characters only
- Confusing sorting with finding unique character
- Assuming it reverses the string
Solution
Step 1: Identify data structure needs
We need to map each character to its count, so a key-value structure is required.Step 2: Choose appropriate Java collection
HashMap stores characters as keys and their counts as values efficiently.Final Answer:
HashMap -> Option BQuick Check:
Use HashMap for character counts [OK]
- Using list which doesn't map keys to counts
- Using TreeSet which stores unique sorted elements only
- Using LinkedList which is not key-value based
String s = "swiss";
HashMap map = new HashMap<>();
for(char c : s.toCharArray()) {
map.put(c, map.getOrDefault(c, 0) + 1);
}
for(char c : s.toCharArray()) {
if(map.get(c) == 1) {
System.out.println(c);
break;
}
}Solution
Step 1: Count character frequencies
Characters and counts: s=3, w=1, i=1.Step 2: Find first character with count 1
Iterate string: 's'(3), 'w'(1) -> first non repeating is 'w'.Final Answer:
w -> Option AQuick Check:
First unique char in "swiss" = w [OK]
- Choosing 's' which repeats
- Choosing 'i' which is unique but appears after 'w'
- Assuming no output if not careful
String s = "hello";
HashMap map = new HashMap<>();
for(int i = 0; i < s.length(); i++) {
map.put(s.charAt(i), 1);
}
for(int i = 0; i < s.length(); i++) {
if(map.get(s.charAt(i)) == 1) {
System.out.println(s.charAt(i));
break;
}
}Solution
Step 1: Analyze map population logic
The code sets count to 1 for every character without incrementing, so repeats are not counted.Step 2: Effect on finding non repeating character
Since all counts are 1, the code incorrectly treats all characters as unique.Final Answer:
The map.put always sets count to 1, ignoring repeats -> Option AQuick Check:
Count update missing causes wrong results [OK]
- Not incrementing counts in map
- Wrong loop indices
- Confusing key types in map
"aabbccddeeffg", which character will be the first non repeating character using the hash method? What if the string is "aabbccddeeffggh"?Solution
Step 1: Analyze first string "aabbccddeeffg"
All characters except 'g' appear twice; 'g' appears once, so first non repeating is 'g'.Step 2: Analyze second string "aabbccddeeffggh"
Now 'g' appears twice, 'h' appears once, so first non repeating is 'h'.Final Answer:
First: g, Second: h -> Option CQuick Check:
Check counts carefully for each string [OK]
- Assuming first character is always unique
- Ignoring updated counts in second string
- Confusing repeated characters as unique
Ready to prove it?
Pass the test and this pattern moves unknown
