Given a stream of characters and we have to find first non repeating character each time a character is inserted to the stream.
Examples:
Input : a a b c
Output : a -1 b b
Input : a a c
Output : a -1 c
We have already discussed a Doubly linked list based approach in the previous post.
Approach:
- Create a count array of size 26(assuming only lower case characters are present) and initialize it with zero.
- Create a queue of char datatype.
- Store each character in queue and increase its frequency in the hash array.
- For every character of stream, we check front of the queue.
- If the frequency of character at the front of queue is one, then that will be the first non-repeating character.
- Else if frequency is more than 1, then we pop that element.
- If queue became empty that means there are no non-repeating characters so we will print -1.
Below is the implementation of above approach:
Time complexity : O(n)
Auxiliary Space : O(n)