What would be the best space and time efficient solution to find the first non repeating character for a string like aabccbdcbe
?
The answer here is d. So the point that strikes me is that it can be done in two ways:
Given a string, find the first non-repeating character in it. For example, if the input string is “GeeksforGeeks”, then the output should be ‘f’ and if the input string is “GeeksQuiz”, then the output should be ‘G’. Become a success story instead of just reading about them.
For every character, check if it repeats or not. If the character repeats, increment count of repeating characters. When the count becomes K, return the character. We can Use Sorting to solve the problem in O (n Log n) time.
Scan the string return character if the count in hash table is 1. Store the repeating and nonRepeating characters separately. At the end of the iteration, the first element of the nonRepeatingChars list is the first non-repeated character.
First, we will calculate the frequency of each character present in the string as non-repeating characters are those that are present in the string only once. Let’s have a look at non repeating character in a string in Java. Take String as a input from the user. Create array of 256 element to store frequency of each character.
A list comprehension will give you the characters in the order they appear if they only appear once:
In [61]: s = 'aabccbdcbe'
In [62]: [a for a in s if s.count(a) == 1]
Out[62]: ['d', 'e']
Then just return the first entry of this:
In [63]: [a for a in s if s.count(a) == 1][0]
Out[63]: 'd'
If you just need the first entry, a generator would work as well:
In [69]: (a for a in s if s.count(a) == 1).next()
Out[69]: 'd'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With