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.