Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to find first non repeating character in a string [duplicate]

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:

  1. For every index i loop i-1 times and check if that character occurs ever again. But this is not efficient: growth of this method is O(N^2) where N is the length of the string.
  2. Another possible good way could be if I could form a tree or any other ds such that I could order the character based on the weights (the occurrence count). This could take me just one loop of length N through the string to form the structure. That is just O(N) + O(time to build tree or any ds).
like image 485
Sandy Avatar asked Mar 19 '13 09:03

Sandy


People also ask

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

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.

How do you check if a character repeats or not?

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.

How to scan for repeating and nonrepeating characters in MySQL?

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.

How to calculate frequency of non repeating character in a string?

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.


1 Answers

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'
like image 155
TyrantWave Avatar answered Oct 31 '22 23:10

TyrantWave