Bird
Raised Fist0
DSA Cprogramming~10 mins

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

Choose your learning style10 modes available
Concept Flow - First Non Repeating Character Using Hash
Start
↓
Create empty hash map
↓
Traverse string: For each char
↓
Increment char count in hash
↓
Traverse string again
↓
Check hash count of char
↓
Return char
↓
If none found, return -1
↓
End
We count each character's frequency using a hash map, then find the first character with count 1.
Execution Sample
DSA C
char str[] = "swiss";
int hash[256] = {0};
for (int i=0; str[i]; i++) hash[(unsigned char)str[i]]++;
for (int i=0; str[i]; i++) if (hash[(unsigned char)str[i]] == 1) return i;
return -1;
Counts characters in 'swiss' then finds first non-repeating character index.
Execution Table
StepOperationCharacter ProcessedHash Count UpdateCurrent Hash State (partial)ActionResult
1Initialize hash map-All zeroAll zerosStart counting-
2Count 's''s'hash['s'] = 1{'s':1}Continue counting-
3Count 'w''w'hash['w'] = 1{'s':1, 'w':1}Continue counting-
4Count 'i''i'hash['i'] = 1{'s':1, 'w':1, 'i':1}Continue counting-
5Count 's''s'hash['s'] = 2{'s':2, 'w':1, 'i':1}Continue counting-
6Count 's''s'hash['s'] = 3{'s':3, 'w':1, 'i':1}Counting done-
7Check first char 's''s'hash['s'] = 3{'s':3, 'w':1, 'i':1}Count > 1, skip-
8Check second char 'w''w'hash['w'] = 1{'s':3, 'w':1, 'i':1}Count == 1, return index 1Index 1
9End----First non-repeating char index = 1
💡 Found first character with count 1 at index 1 ('w'), stop.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5After Step 6After Step 7After Step 8Final
hash['s']011123333
hash['w']001111111
hash['i']000111111
i (index)000000111
Key Moments - 3 Insights
Why do we need two passes over the string?
The first pass counts all characters (see steps 2-6), the second pass finds the first with count 1 (steps 7-8). We can't find the first non-repeating character in one pass because counts are unknown initially.
Why do we use a hash map with size 256?
Because we assume ASCII characters, each character maps to an index 0-255 in the hash array to count frequency efficiently (shown in variable_tracker).
What if no non-repeating character exists?
If no character has count 1 after second pass, the function returns -1 (not shown in this example but implied after step 9).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 6, what is the count of 's' in the hash?
A1
B2
C3
D0
💡 Hint
Check the 'Hash Count Update' and 'Current Hash State' columns at step 6.
At which step does the algorithm find the first non-repeating character?
AStep 7
BStep 8
CStep 6
DStep 9
💡 Hint
Look at the 'Action' and 'Result' columns in the execution_table.
If the input string was "aabbcc", what would the final result be?
AIndex 0
BIndex 1
C-1
DIndex 2
💡 Hint
No character appears once, so the function returns -1 as per the exit_note.
Concept Snapshot
First Non Repeating Character Using Hash
- Use a hash map (array) to count character frequencies
- First pass: count all chars
- Second pass: find first char with count 1
- Return index or -1 if none
- Works in O(n) time with O(1) space for ASCII
Full Transcript
This concept finds the first character in a string that does not repeat. It uses a hash map to count how many times each character appears. First, it goes through the string and counts each character. Then, it goes through the string again to find the first character with count one. If found, it returns the index of that character. Otherwise, it returns -1. This method is efficient and works well for ASCII characters.

Practice

(1/5)
1. What is the main purpose of using a hash (like a dictionary or map) to find the first non-repeating character in a string?
easy
A. To reverse the string quickly
B. To sort the characters alphabetically
C. To remove duplicate characters from the string
D. To count the frequency of each character efficiently

Solution

  1. Step 1: Understand the role of hash in counting

    A hash (dictionary) stores characters as keys and their counts as values, allowing quick frequency counting.
  2. Step 2: Identify why frequency counting helps

    Knowing how many times each character appears helps find the first character with count 1, which is the first non-repeating character.
  3. Final Answer:

    To count the frequency of each character efficiently -> Option D
  4. Quick Check:

    Hash counts characters = frequency count [OK]
Hint: Use hash to count chars, then find first with count 1 [OK]
Common Mistakes:
  • Thinking hash sorts characters
  • Assuming hash reverses string
  • Using hash to remove duplicates only
2. Which of the following C code snippets correctly initializes a hash map (using an array) to count characters for ASCII strings?
easy
A. int count[256] = {0};
B. int count[] = NULL;
C. int count[256]; // uninitialized
D. int count = 256;

Solution

  1. Step 1: Check correct array initialization

    In C, to count ASCII chars, an int array of size 256 initialized to zero is needed: int count[256] = {0};
  2. Step 2: Identify incorrect options

    int count[] = NULL; sets pointer to NULL, no array. int count[256]; // uninitialized is uninitialized, may contain garbage. int count = 256; is a single int, not array.
  3. Final Answer:

    int count[256] = {0}; -> Option A
  4. Quick Check:

    Array size 256 with zero init = correct hash map [OK]
Hint: Use int count[256] = {0} for ASCII char frequency [OK]
Common Mistakes:
  • Not initializing array to zero
  • Using pointer instead of array
  • Declaring single int instead of array
3. What will be the output of the following C code snippet?
char str[] = "swiss";
int count[256] = {0};
for (int i = 0; str[i] != '\0'; i++) {
    count[(int)str[i]]++;
}
for (int i = 0; str[i] != '\0'; i++) {
    if (count[(int)str[i]] == 1) {
        printf("%c", str[i]);
        break;
    }
}
medium
A. s
B. i
C. w
D. No output

Solution

  1. Step 1: Count character frequencies in "swiss"

    Characters: s(3 times), w(1 time), i(1 time)
  2. Step 2: Find first character with count 1 in order

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

    w -> Option C
  4. Quick Check:

    First unique char in "swiss" = w [OK]
Hint: Check counts, print first char with count 1 [OK]
Common Mistakes:
  • Printing first char without checking count
  • Confusing 'i' and 'w' counts
  • Ignoring character order
4. Identify the bug in this C code snippet that tries to find the first non-repeating character:
char str[] = "hello";
int count[256];
for (int i = 0; str[i] != '\0'; i++) {
    count[(int)str[i]]++;
}
for (int i = 0; str[i] != '\0'; i++) {
    if (count[(int)str[i]] == 1) {
        printf("%c", str[i]);
        break;
    }
}
medium
A. count array is not initialized to zero
B. Loop condition is incorrect
C. Casting char to int is wrong
D. printf format specifier is incorrect

Solution

  1. Step 1: Check count array initialization

    count array is declared but not initialized, so it contains garbage values causing wrong counts.
  2. Step 2: Explain impact of uninitialized array

    Incrementing garbage values leads to incorrect frequency counts, so first non-repeating char cannot be found correctly.
  3. Final Answer:

    count array is not initialized to zero -> Option A
  4. Quick Check:

    Uninitialized count array causes wrong frequency [OK]
Hint: Always initialize count array to zero before counting [OK]
Common Mistakes:
  • Forgetting to initialize count array
  • Assuming default zero initialization
  • Misusing loop conditions
5. Given the string "aabbccddeffg", which character will be identified as the first non-repeating character using a hash map counting method? Consider the code below:
char str[] = "aabbccddeffg";
int count[256] = {0};
for (int i = 0; str[i] != '\0'; i++) {
    count[(int)str[i]]++;
}
for (int i = 0; str[i] != '\0'; i++) {
    if (count[(int)str[i]] == 1) {
        printf("%c", str[i]);
        break;
    }
}
hard
A. g
B. e
C. d
D. f

Solution

  1. Step 1: Count frequencies of each character

    Characters and counts: a(2), b(2), c(2), d(2), e(1), f(2), g(1)
  2. Step 2: Find first character with count 1 in order

    Order: a,b,c,d,e,f,g; e and g have count 1, but e appears before g.
  3. Step 3: Check carefully the string order

    String is "aabbccddeffg"; 'e' appears once at position 8, 'g' at position 11. So first non-repeating is 'e'.
  4. Final Answer:

    e -> Option B
  5. Quick Check:

    First unique char in string = e [OK]
Hint: Check counts and order carefully to find first unique char [OK]
Common Mistakes:
  • Choosing last unique char instead of first
  • Ignoring character order in string
  • Miscounting character frequencies
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