I read of a job interview question to write some code for the following:
Write an efficient function to find the first nonrepeated character in a st
def non_repeating(given_string):
try:
item = [x for x in given_string[:] if given_string[:].count(x) == 1][0]
except:
return None
else:
return item
# NOTE: The following input values will be used for testing your solution.
print non_repeating("abcab") # should return 'c'
print non_repeating("abab") # should return None
print non_repeating("aabbbc") # should return 'c'
print non_repeating("aabbdbc") # should return 'd'
Simple Python3 solution
def findFirstUniqueChar(s):
d = {}
for c in s:
if c in d:
d[c] += 1
else:
d[c] = 1
for c in s:
if d[c] == 1:
return s.index(c)
return -1
The idea here is to initialize an array with some default value , for example 0. And when you come across a particular character in the string, you just increase the counter using the ASCII value of that character in the array you defined initially.
As you pass through the string, you have to update the respective counters for the character in the array. Now one will require to go through the array one more time, and check if there is any value which is equal to 1, if there is - Just return that character as a first non-repeated character in a given string.
class FindFirstUniqueChar
{
private static char ReturnFirstUniqueChar(string sampleString)
{
// Initialize a sample char array and convert your string to char array.
char[] samplechar = sampleString.ToCharArray();
// The default array will have all value initialized as 0 - it's an int array.
int[] charArray = new int[256];
// Go through the loop and update the counter in respective value of the array
for (int i = 0; i < samplechar.Length; i++)
{
charArray[samplechar[i]] = charArray[samplechar[i]] + 1;
}
// One more pass - which will provide you the first non-repeated char.
for (int i = 0; i < charArray.Length; i++)
{
if (charArray[samplechar[i]] == 1)
{
return samplechar[i];
}
}
// Code should not reach here. If it returns '\0'
// that means there was no non-repeated char in the given string.
return '\0';
}
static void Main(string[] args)
{
Console.WriteLine("The First Unique char in given String is: " +
ReturnFirstUniqueChar("ABCA"));
Console.ReadLine();
}
}
I have provided just a sample code. It doesn't include error check and edge cases. For those who are Interested to know the time complexity of the give algorithm - It is O(N) + O(N) = O(2N) which is nearly O(N). It does use an extra memory space. Your feedback is welcome.
Python; O(N+N) I think.
def find_first_non_occuring(test_str):
results = {}
for letter in test_str:
if letter in results.keys():
if results[letter] == 1:
results[letter] = results[letter]+1
else:
results[letter] = 1
for letter in test_str:
if results[letter] is 1:
return letter
test_str = 'afixuboshafe fafd weagdgdg'
print find_first_non_occuring(test_str)
def firstNotRepeatingCharacter(s):
for c in s:
if s.find(c) == s.rfind(c):
return c
return '_'
I think the worst case is O(n^2) but looks clear for me:
def firstNonRep(word):
"""the first non-repeating character in a string: "ABCA" -> B """
for (i, c) in enumerate(word):
residual = word[i+1:]
if not c in residual:
return c