Queue based approach for first non-repeating character in a stream

2.9

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-

  1. Create a count array of size 26(assuming only lower case characters are present) and initialize it with zero.
  2. Create a queue of char datatype.
  3. Store each character in queue and increase its frequency in the hash array.
  4. For every character of stream, we check front of the queue.
  5. If the frequency of character at the front of queue is one, then that will be the first non repeating character.
  6. Else if frequency is more than 1, then we pop that element.
  7. If queue became empty that means there are no non repeating character so we will print -1.

C++

// C++ program for a Queue based approach to find first non-repeating
// character
#include <bits/stdc++.h>
using namespace std;
const int CHAR_MAX = 26;

// function to find first non repeating
// character of sa stream
void firstnonrepeating(char str[])
{
    queue<char> q;
    int charCount[CHAR_MAX] = { 0 };

    // traverse whole stream
    for (int i = 0; str[i]; i++) {

        // push each character in queue
        q.push(str[i]);

        // increment the frequency count
        charCount[str[i]-'a']++;

        // check for the non pepeating character
        while (!q.empty())
        {
            if (charCount[q.front()-'a'] > 1)
                q.pop();
            else
            {
                cout << q.front() << " ";
                break;
            }
        }

        if (q.empty())
            cout << -1 << " ";
    }
    cout << endl;
}

// Driver function
int main()
{
    char str[] = "aabc";
    firstnonrepeating(str);
    return 0;
}

Java

//Java Program for a Queue based approach to find first non-repeating
//character

import java.util.LinkedList;
import java.util.Queue;

public class NonReapatingCQueue 
{
	 final static int CHAR_MAX = 26;
	 
	// function to find first non repeating
	// character of stream
	 static void firstNonRepeating(String str)
	 {
		 //count array of size 26(assuming only lower case characters are present) 
		 int[] charCount = new int[CHAR_MAX];
		 
		 //Queue to store Characters
		 Queue<Character> q = new LinkedList<Character>();
		 
		// traverse whole stream
		 for(int i=0; i<str.length(); i++)
		 {
			 char c = str.charAt(i);
			 
			// push each character in queue
			 q.add(c);
			 
			// increment the frequency count
			 charCount1++;
			 
			// check for the non repeating character
			 while(!q.isEmpty())
			 {
				 if(charCount[q.peek() - 'a'] > 1)
					 q.remove();
				 else
				 {
					 System.out.print(q.peek() + " ");
					 break;
				 }
			 }
			 if(q.isEmpty())
				 System.out.print(-1 + " ");
		 }
		 System.out.println();
	 }

	// Driver function
	public static void main(String[] args) 
	{
		String str = "aabc";
		firstNonRepeating(str);
	}

}
//This code is Contributed by Sumit Ghosh


Output:

a -1 b b

This article is contributed by Niteesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



2.9 Average Difficulty : 2.9/5.0
Based on 13 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.