First Non Repeating Character Using Hash in DSA Python - 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.
from collections import Counter
def first_non_repeating_char(s: str) -> int:
count = Counter(s) # Count each character
for i, ch in enumerate(s):
if count[ch] == 1:
return i
return -1
This code counts characters, then finds the first one that appears only once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Counting characters and then scanning the string again.
- How many times: Counting loops over all characters once; scanning again loops over all characters once.
As the string gets longer, the counting and scanning both take longer, roughly doubling the work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 operations (count + scan) |
| 100 | About 200 operations |
| 1000 | About 2000 operations |
Pattern observation: Operations grow roughly twice the input size, so growth is linear.
Time Complexity: O(n)
This means the time to find the first non-repeating character grows directly with the string length.
[X] Wrong: "Since we scan twice, the time is O(n²)."
[OK] Correct: Each scan goes through the string once, so total work is about 2n, which is still O(n), not squared.
Understanding this helps you explain how hashing speeds up searching tasks, a key skill 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: Identify the main operation
It uses a hash (dictionary) to count occurrences and then finds the first character with count 1.Final Answer:
Finds the first character in a string that appears only once -> Option AQuick Check:
First unique character = first non repeating character [OK]
- Thinking it counts total characters instead of unique
- Confusing sorting with finding unique characters
- Assuming it reverses the string
s?Solution
Step 1: Check dictionary initialization and update
counts = {}; for ch in s: counts[ch] = counts.get(ch, 0) + 1 correctly creates an empty dictionary and updates counts using get with default 0.Step 2: Analyze other options
counts = []; for ch in s: counts[ch] += 1 uses a list which cannot be indexed by characters; counts = set(); for ch in s: counts.add(ch) uses a set which only stores unique items without counts; counts = 0; for ch in s: counts += 1 uses an integer which cannot store counts per character.Final Answer:
counts = {}; for ch in s: counts[ch] = counts.get(ch, 0) + 1 -> Option BQuick Check:
Dictionary with get method counts chars correctly [OK]
- Using list instead of dictionary for counts
- Using set which does not count duplicates
- Trying to increment integer without keys
def first_non_repeating(s):
counts = {}
for ch in s:
counts[ch] = counts.get(ch, 0) + 1
for ch in s:
if counts[ch] == 1:
return ch
return '_'
print(first_non_repeating('swiss'))Solution
Step 1: Count character occurrences in 'swiss'
Counts: s=3, w=1, i=1Step 2: Find first character with count 1 in order
Order: s (3), w (1) -> first non repeating is 'w'Final Answer:
w -> Option DQuick Check:
First unique char in 'swiss' is 'w' [OK]
- Returning first unique char incorrectly as 's'
- Confusing 'i' as first unique instead of 'w'
- Returning '_' when unique char exists
def first_non_repeating_bug(s):
counts = {}
for ch in s:
counts[ch] += 1
for ch in s:
if counts[ch] == 1:
return ch
return '_'Solution
Step 1: Analyze counts dictionary usage
The code tries to increment counts[ch] without initializing counts[ch], causing KeyError.Step 2: Identify missing initialization
Must initialize counts[ch] to 0 before increment or use counts.get(ch, 0) + 1.Final Answer:
counts dictionary is not initialized with default values before increment -> Option CQuick Check:
Missing initialization causes KeyError [OK]
- Assuming return '_' is unreachable
- Thinking loop over s is wrong
- Believing function returns nothing
s = 'aabbccddeeffg', which character will the first non repeating character algorithm return?Note: The algorithm uses a hash to count characters and returns the first character with count 1 or '_' if none.
Solution
Step 1: Count occurrences of each character in 'aabbccddeeffg'
a=2, b=2, c=2, d=2, e=2, f=2, g=1Step 2: Find first character with count 1 in string order
All characters except 'g' repeat twice; 'g' appears once at the end.Final Answer:
g -> Option AQuick Check:
Only 'g' is unique in the string [OK]
- Choosing 'a' or 'f' which repeat twice
- Choosing '_' when unique char exists
- Ignoring order of characters
Ready to prove it?
Pass the test and this pattern moves unknown
