First Non Repeating Character in a Stream of Characters

Find the first non-repeating character in a stream of characters.

Given a string A denoting a stream of lowercase alphabets. We have to write a code to make a new string B.

Here is the rule to form string B.

i) We have to find the first non-repeating character each time a character is inserted into the stream and append it at the end to B.

ii) If no non-repeating character is found then append ‘#’ at the end of B.

For example – 

Example 1 –

Input   = “abadbc”

Output  = “aabbdd”

Explanation:

“a”      –   From the stream, the first character is a, So at this point, the first non-repeating character is ‘a’.

“ab”     –   When b comes, Still the first non-repeating character is ‘a’.

“aba”    –   This time the character is a. Character a is repeated twice so the first non repeating character is ‘b’

“abad”   –   When character d comes, the first non-repeating character is ‘b’.

“abadb”  –   When character b comes, its count is 2 now. So the first non-repeating character at this point is ‘d’.

“abadbc” –   Next character is c. At this point, the first non-repeating character is ‘d’.

Example 2 –

Input  = “abdabd”

Output = “aaabd#”

First Non Repeating Character in a Stream

We have discussed the problem statement. The next question is how do we approach this problem? Which data structure should we use?

The easiest version of this problem is to find first non-repeating character in a string. When the complete string is given instead of one character is coming at a time from the stream, then we can easily solve the problem using HashMap.

In this case, We can’t be able to solve a problem by simply using HashMap. We need another data structure to maintain the character order.

Also, I have shared the video tutorial link at the end of this post.

First Non Repeating Character in a Stream of Characters – Java Code

In this example, I am going to example how we can solve this problem using HashMap and Queue data structure.

Here are the following steps –

i) When a character comes from the stream, we put the character and its count in a HashMap. Also, we enqueue that character in a queue.

ii) If its count is 1, then we append that character in a new string. Else we poll the queue until we found the character whose count is 1. If a queue is empty then we append #.

Sort Characters by Frequency

Find first non-repeating character in a stream of characters video tutorial

Programming Video Tutorials

Programming questions on string

Tagged . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.