WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Coding Interview Essentials · Array and String Problems · question 34 of 120

How do you find the first non-repeating character in a string?

📕 Buy this interview preparation book: 120 Coding Interview Essentials questions & answers — PDF + EPUB for $5

Finding the first non-repeating character in a string is a problem that can be solved using hashing. The basic idea is to get the frequency count of all the characters and find the one with a count of 1.

Here are the steps in Python:

1. Create a hash table to store the count of each character in the string as ‘charCount‘. The key will be the character itself and the value is the count.

2. Iterate through the string in order (this is important as we are looking for the first non-repeating character). As we go, add the characters to the ‘charCount‘ hash table and increment their count value.

3. After we have counted all characters, iterate through the string in the original order again. This time, check the ‘charCount‘ for each character. Return the first character that has a count of 1.

Here’s an example code:

def firstUniqChar(s):
    charCount = {}
    
    # Get character count.
    for c in s:
        if c not in charCount:
            charCount[c] = 1
        else:
            charCount[c] += 1
    
    # Find the first non-repeating character.
    for c in s:
        if charCount[c] == 1:
            return c
    
    return None

You can test it with some string:

print(firstUniqChar('interviewQuery'))  # returns 'i'
print(firstUniqChar('codesignal'))  # returns 'c'

Note that this solution assumes that the string contains only ASCII characters. If the string can contain any unicode characters then the hash table needs to be updated to accommodate these.

This solution has a time complexity of O(n) where n is the size of the string. This is because we perform a single pass to count the characters, and a second pass to find the first unique character. The space complexity is also O(n) for the storage required for the hash table.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Coding Interview Essentials interview — then scores it.
📞 Practice Coding Interview Essentials — free 15 min
📕 Buy this interview preparation book: 120 Coding Interview Essentials questions & answers — PDF + EPUB for $5

All 120 Coding Interview Essentials questions · All topics