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

15 Feb, 2022
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.
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: 
C++
Java
Python3
C#
Javascript
// C++ program for a Queue based approach // to find first non-repeating character#include <bits/stdc++.h>using namespace std;const int MAX_CHAR = 26;  // function to find first non repeating// character of sa streamvoid firstnonrepeating(char str[]){    queue<char> q;    int charCount[MAX_CHAR] = { 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 repeating 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 functionint main(){    char str[] = "aabc";    firstnonrepeating(str);    return 0;}
// 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 MAX_CHAR = 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[MAX_CHAR];          // Queue to store Characters        Queue<Character> q = new LinkedList<Character>();          // traverse whole stream        for (int i = 0; i < str.length(); i++) {            char ch = str.charAt(i);              // push each character in queue            q.add(ch);              // increment the frequency count            charCount[ch - 'a']++;              // 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
# Python3 program for a Queue based approach # to find first non-repeating character from queue import Queue   # function to find first non # repeating character of sa Stream def firstnonrepeating(Str):    global MAX_CHAR    q = Queue()    charCount = [0] * MAX_CHAR           # traverse whole Stream    for i in range(len(Str)):          # push each character in queue         q.put(Str[i])           # increment the frequency count         charCount[ord(Str[i]) -                   ord('a')] += 1          # check for the non repeating        # character         while (not q.empty()):             if (charCount[ord(q.queue[0]) -                           ord('a')] > 1):                 q.get()             else:                print(q.queue[0], end = " ")                 break          if (q.empty()):             print(-1, end = " ")    print()  # Driver CodeMAX_CHAR = 26Str = "aabc"firstnonrepeating(Str)  # This code is contributed by PranchalK
using System;using System.Collections.Generic;  // C# Program for a Queue based approach  // to find first non-repeating character     public class NonReapatingCQueue{    public const int MAX_CHAR = 26;      // function to find first non repeating     // character of stream     public static void firstNonRepeating(string str)    {        // count array of size 26(assuming         // only lower case characters are present)         int[] charCount = new int[MAX_CHAR];          // Queue to store Characters         LinkedList<char> q = new LinkedList<char>();          // traverse whole stream         for (int i = 0; i < str.Length; i++)        {            char ch = str[i];              // push each character in queue             q.AddLast(ch);              // increment the frequency count             charCount[ch - 'a']++;              // check for the non repeating character             while (q.Count > 0)            {                if (charCount[q.First.Value - 'a'] > 1)                {                    q.RemoveFirst();                }                else                {                    Console.Write(q.First.Value + " ");                    break;                }            }            if (q.Count == 0)            {                Console.Write(-1 + " ");            }        }        Console.WriteLine();    }      // Driver function     public static void Main(string[] args)    {        string str = "aabc";        firstNonRepeating(str);    }}  //This code is contributed by Shrikant13
<script>        // JavaScript Program for a Queue based approach      // to find first non-repeating character        const MAX_CHAR = 26;        // function to find first non repeating      // character of stream      function firstNonRepeating(str) {        // count array of size 26(assuming        // only lower case characters are present)        var charCount = new Array(MAX_CHAR).fill(0);          // Queue to store Characters        var q = [];          // traverse whole stream        for (var i = 0; i < str.length; i++) {          var ch = str[i];            // push each character in queue          q.push(ch);            // increment the frequency count          charCount[ch.charCodeAt(0) - "a".charCodeAt(0)]++;            // check for the non repeating character          while (q.length > 0) {            if (charCount[q[0].charCodeAt(0) -             "a".charCodeAt(0)] > 1) {              q.shift();            } else {              document.write(q[0] + " ");              break;            }          }          if (q.length == 0) {            document.write(-1 + " ");          }        }        document.write("<br>");      }        // Driver function      var str = "aabc";      firstNonRepeating(str);        </script>
a -1 b b
 
  Video:  
YouTubeGeeksforGeeks507K subscribersQueue based approach for first non-repeating character in a stream | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:03•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Jkx1vP3ZkK0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Niteesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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. 
shrikanth13
PranchalKatiyar
ParulShandilya
rdtank
Amazon
array-stream
Flipkart
Microsoft
Payu
Yahoo
Hash
Linked List
Queue
Strings
Flipkart
Amazon
Microsoft
Payu
Yahoo
Linked List
Hash
Strings
Queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Hashing | Set 2 (Separate Chaining)
Sort string of characters
Counting frequencies of array elements
Most frequent element in an array
Sorting a Map by value in C++ STL
Linked List | Set 1 (Introduction)
Linked List | Set 2 (Inserting a node)
Reverse a linked list
Stack Data Structure (Introduction and Program)
Linked List | Set 3 (Deleting a node)