Bird
Raised Fist0
DSA Pythonprogramming~10 mins

First Non Repeating Character Using Hash in DSA Python - Execution Trace

Choose your learning style10 modes available
Concept Flow - First Non Repeating Character Using Hash
Start with input string
↓
Create empty hash map for counts
↓
For each char in string
↓
Increment char count in hash map
↓
For each char in string
↓
Check if char count is 1?
No→Continue
Yes↓
Return this char as first non repeating
↓
If none found, return None or -1
Count characters using a hash map, then find the first character with count 1.
Execution Sample
DSA Python
def first_non_repeating_char(s):
    counts = {}
    for c in s:
        counts[c] = counts.get(c, 0) + 1
    for c in s:
        if counts[c] == 1:
            return c
    return None
This code finds the first character in the string that appears only once.
Execution Table
StepOperationCharacter ProcessedHash Map StateCheck ConditionResult / Action
1Initialize hash map-{}-Empty hash map created
2Count chara{"a":1}-Count 'a' as 1
3Count charb{"a":1, "b":1}-Count 'b' as 1
4Count charc{"a":1, "b":1, "c":1}-Count 'c' as 1
5Count chara{"a":2, "b":1, "c":1}-Increment 'a' count to 2
6Count charb{"a":2, "b":2, "c":1}-Increment 'b' count to 2
7Count chard{"a":2, "b":2, "c":1, "d":1}-Count 'd' as 1
8Check first non repeatinga{"a":2, "b":2, "c":1, "d":1}counts['a'] == 1?No, count is 2, continue
9Check first non repeatingb{"a":2, "b":2, "c":1, "d":1}counts['b'] == 1?No, count is 2, continue
10Check first non repeatingc{"a":2, "b":2, "c":1, "d":1}counts['c'] == 1?Yes, count is 1, return 'c'
11Return result---First non repeating character is 'c'
💡 Found first character with count 1 at step 10, returned 'c'
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5After Step 6After Step 7After Step 10Final
counts{}{"a":1}{"a":1, "b":1}{"a":1, "b":1, "c":1}{"a":2, "b":1, "c":1}{"a":2, "b":2, "c":1}{"a":2, "b":2, "c":1, "d":1}{"a":2, "b":2, "c":1, "d":1}{"a":2, "b":2, "c":1, "d":1}
current_char-abcabdcc
resultNoneNoneNoneNoneNoneNoneNonecc
Key Moments - 3 Insights
Why do we need two loops instead of one?
The first loop counts all characters, building the hash map (see steps 2-7). The second loop checks the original order to find the first character with count 1 (steps 8-10). Doing both in one loop would miss order.
What if no character has count 1?
If no character count is 1, the second loop finishes without returning (not shown in table). Then the function returns None (step 11). This means no non repeating character exists.
Why do we check counts[c] == 1 and not counts[c] > 0?
We want the first character that appears exactly once. Counts greater than 1 mean repeating characters, so we skip those (see steps 8-9).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the hash map state after processing character 'b' the second time?
A{"a":2, "b":2, "c":1}
B{"a":1, "b":2, "c":1}
C{"a":2, "b":1, "c":1}
D{"a":2, "b":2, "c":2}
💡 Hint
Check step 6 in the execution table where 'b' is processed the second time.
At which step does the function find the first non repeating character?
AStep 9
BStep 10
CStep 8
DStep 11
💡 Hint
Look at the 'Check first non repeating' operations and when the condition counts[c] == 1 is true.
If the input string was 'aabbcc', what would the function return?
A'a'
B'b'
CNone
D'c'
💡 Hint
Refer to the key moments about what happens if no character has count 1.
Concept Snapshot
Use a hash map to count characters.
First loop: count all characters.
Second loop: find first char with count 1.
Return that char or None if none found.
Preserves original order.
Simple and efficient approach.
Full Transcript
This concept finds the first non repeating character in a string using a hash map. First, it counts how many times each character appears by looping through the string once. Then, it loops again through the string in original order to find the first character whose count is exactly one. If found, it returns that character; otherwise, it returns None. This method ensures the order is preserved and is efficient because it uses hashing for counting.

Practice

(1/5)
1. What does the "First Non Repeating Character Using Hash" algorithm primarily do?
easy
A. Finds the first character in a string that appears only once
B. Counts the total number of characters in a string
C. Sorts characters of a string alphabetically
D. Reverses the string

Solution

  1. Step 1: Understand the problem goal

    The algorithm aims to find the first character in the string that does not repeat anywhere else.
  2. Step 2: Identify the main operation

    It uses a hash (dictionary) to count occurrences and then finds the first character with count 1.
  3. Final Answer:

    Finds the first character in a string that appears only once -> Option A
  4. Quick Check:

    First unique character = first non repeating character [OK]
Hint: Look for the first character with count one in the hash [OK]
Common Mistakes:
  • Thinking it counts total characters instead of unique
  • Confusing sorting with finding unique characters
  • Assuming it reverses the string
2. Which of the following Python code snippets correctly initializes a hash (dictionary) to count characters in a string s?
easy
A. counts = []; for ch in s: counts[ch] += 1
B. counts = {}; for ch in s: counts[ch] = counts.get(ch, 0) + 1
C. counts = set(); for ch in s: counts.add(ch)
D. counts = 0; for ch in s: counts += 1

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    counts = {}; for ch in s: counts[ch] = counts.get(ch, 0) + 1 -> Option B
  4. Quick Check:

    Dictionary with get method counts chars correctly [OK]
Hint: Use dict.get(key, 0) to count characters safely [OK]
Common Mistakes:
  • Using list instead of dictionary for counts
  • Using set which does not count duplicates
  • Trying to increment integer without keys
3. What is the output of the following code?
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'))
medium
A. s
B. _
C. i
D. w

Solution

  1. Step 1: Count character occurrences in 'swiss'

    Counts: s=3, w=1, i=1
  2. Step 2: Find first character with count 1 in order

    Order: s (3), w (1) -> first non repeating is 'w'
  3. Final Answer:

    w -> Option D
  4. Quick Check:

    First unique char in 'swiss' is 'w' [OK]
Hint: Check counts then scan string for first count 1 char [OK]
Common Mistakes:
  • Returning first unique char incorrectly as 's'
  • Confusing 'i' as first unique instead of 'w'
  • Returning '_' when unique char exists
4. The following code is intended to find the first non repeating character but has a bug. What is the bug?
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 '_'
medium
A. The for loop should iterate over counts.keys() instead of s
B. The return '_' statement is unreachable
C. counts dictionary is not initialized with default values before increment
D. The function does not return anything

Solution

  1. Step 1: Analyze counts dictionary usage

    The code tries to increment counts[ch] without initializing counts[ch], causing KeyError.
  2. Step 2: Identify missing initialization

    Must initialize counts[ch] to 0 before increment or use counts.get(ch, 0) + 1.
  3. Final Answer:

    counts dictionary is not initialized with default values before increment -> Option C
  4. Quick Check:

    Missing initialization causes KeyError [OK]
Hint: Initialize counts[ch] before increment or use get() [OK]
Common Mistakes:
  • Assuming return '_' is unreachable
  • Thinking loop over s is wrong
  • Believing function returns nothing
5. Given the string 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.
medium
A. g
B. a
C. _
D. f

Solution

  1. Step 1: Count occurrences of each character in 'aabbccddeeffg'

    a=2, b=2, c=2, d=2, e=2, f=2, g=1
  2. Step 2: Find first character with count 1 in string order

    All characters except 'g' repeat twice; 'g' appears once at the end.
  3. Final Answer:

    g -> Option A
  4. Quick Check:

    Only 'g' is unique in the string [OK]
Hint: Check counts; last unique char is first non repeating here [OK]
Common Mistakes:
  • Choosing 'a' or 'f' which repeat twice
  • Choosing '_' when unique char exists
  • Ignoring order of characters
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard