The Wayback Machine - https://web.archive.org/web/20240624021339/https://www.geeksforgeeks.org/queue-based-approach-for-first-non-repeating-character-in-a-stream/
Open In App

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

Last Updated : 10 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 characters so we will print -1.

Below is the implementation of above approach:

C++




// 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 stream
void 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 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 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




# 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 Code
MAX_CHAR = 26
Str = "aabc"
firstnonrepeating(Str)
  
# This code is contributed by PranchalK


C#




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


Javascript




<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>


Output: 

a -1 b b

 

Time complexity : O(n) 
Auxiliary Space : O(n)



Similar Reads

Find the first non-repeating character from a stream of characters
Given a stream of characters, find the first non-repeating character from the stream. You need to tell the first non-repeating character in O(1) time at any moment. If we follow the first approach discussed here, then we need to store the stream so that we can traverse it one more time to find the first non-repeating character at any moment. If we
15+ min read
Queries to find the first non-repeating character in the sub-string of a string
Given a string str, the task is to answer Q queries where every query consists of two integers L and R and we have to find the first non-repeating character in the sub-string str[L...R]. If there is no non-repeating character then print -1. Examples: Input: str = "GeeksForGeeks", q[] = {{0, 3}, {2, 3}, {5, 12}} Output: G e F Sub-string for the quer
10 min read
Find first non-repeating character in a given string using Linked List
Given a string str of length L, the task is to find the first occurrence of a non-repeating character in the string. Examples: Input: str = "geeksforgeeks"Output: f Input: str = "programmer"Output: p Note: Please refer this article for HashMap approach and this article as space-optimized approach. Linked List Approach: The idea is to use Linked Lis
4 min read
Find first non-repeating character of given String
Given a string S consisting of lowercase Latin Letters, the task is to find the first non-repeating character in S. Examples: Input: "geeksforgeeks"Output: fExplanation: As 'f' is first character in the string which does not repeat. Input: "algorithm"Output: aExplanation: As 'a' is first character in the string which does not repeat. Recommended Pr
15+ min read
First non-repeating character using one traversal of string | Set 2
Given a string, find the first non-repeating character in it. For example, if the input string is "GeeksforGeeks", then output should be 'f' and if input string is "GeeksQuiz", then output should be 'G'. Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. We have discussed two solutions in Given a string, find its f
15+ min read
Find the two non-repeating elements in an array of repeating elements/ Unique Numbers 2
Given an array arr[] containing 2*N+2 positive numbers, out of which 2*N numbers exist in pairs whereas the other two number occur exactly once and are distinct. Find the other two numbers. Return in increasing order. Example: Input: N = 2, arr[] = {1, 2, 3, 2, 1, 4}Output:3 4 Explanation: 3 and 4 occur exactly once. Input: N = 1, arr[] = {2, 1, 3,
9 min read
Should we declare as Queue or Priority Queue while using Priority Queue in Java?
Queue: Queue is an Interface that extends the collection Interface in Java and this interface belongs to java.util package. A queue is a type of data structure that follows the FIFO (first-in-first-out ) order. The queue contains ordered elements where insertion and deletion of elements are done at different ends. Priority Queue and Linked List are
3 min read
Find the last non repeating character in string
Given a string str, the task is to find the last non-repeating character in it. For example, if the input string is "GeeksForGeeks", then the output should be 'r' and if the input string is "GeeksQuiz" then the output should be 'z'. if there is no non-repeating character then print -1.Examples: Input: str = "GeeksForGeeks" Output: r 'r' is the firs
5 min read
Queries to find the last non-repeating character in the sub-string of a given string
Given a string str, the task is to answer Q queries where every query consists of two integers L and R and we have to find the last non-repeating character in the sub-string str[L...R]. If there is no non-repeating character then print -1.Examples: Input: str = "GeeksForGeeks", q[] = {{2, 9}, {2, 3}, {0, 12}} Output: G k r Sub-string for the querie
11 min read
K’th Non-repeating Character in Python using List Comprehension and OrderedDict
Given a string and a number k, find the k-th non-repeating character in the string. Consider a large input string with lacs of characters and a small character set. How to find the character by only doing only one traversal of input string? Examples: Input : str = geeksforgeeks, k = 3 Output : r First non-repeating character is f, second is o and t
2 min read
three90RightbarBannerImg