First non-repeating character in a stream | Practice | GeeksforGeeks

Given an input stream of A of n characters consisting only of lower case alphabets. The task is to find the first non repeating character, each time a character is inserted to the stream. If there is no such character then append '#' to the answer.
 
Example 1:
Input: A = "aabc"
Output: "a#bb"
Explanation: For every character first non
repeating character is as follow-
"a" - first non-repeating character is 'a'
"aa" - no non-repeating character so '#'
"aab" - first non-repeating character is 'b'
"aabc" - first non-repeating character is 'b'

Example 2:
Input: A = "zz"
Output: "z#"
Explanation: For every character first non
repeating character is as follow-
"z" - first non-repeating character is 'z'
"zz" - no non-repeating character so '#'

 
Your Task:
You don't need to read or print anything. Your task is to complete the function FirstNonRepeating() which takes A as input parameter and returns a string after processing the input stream.
 
Expected Time Complexity: O(26 * n)
Expected Space Complexity: O(26)
 
Constraints:
1 <= n <= 105
0
anmol rawat2 days ago
class Solution {public: string FirstNonRepeating(string A){     // Code here     queue<char>q;     string ans="";     unordered_map<char,int>mp;          for(int i=0;i<A.size();i++){         mp[A[i]]++;                  if(mp[A[i]]==1)         q.push(A[i]);                  while(!q.empty()){             if(mp[q.front()]==1)             break;             q.pop();         }                  ans+= q.empty()?'#':q.front();     }     return ans; }};
0
tupesanket19993 days ago
C++ SOLUTION USING QUEUE
Total Time Taken: 0.11/1.77
 string FirstNonRepeating(string A){
     unordered_map<char,long long>rep;
     queue<char>q;
     string s="";
     for(long long i=0;i<A.size();i++){
         if(rep[A[i]]==0){
             rep[A[i]]++;
             q.push(A[i]);
         }else{
             rep[A[i]]++;
         }
         while(!q.empty() && rep[q.front()]>=2)q.pop();
         if(!q.empty()){
             s+=q.front();
         }else{
             s+='#';
         }
     }
     return s;
 }
0
deeptimayeemaharana064 days ago
CAN SOMEONE PLEASE CORRECT MY CODE??
class Solution {  struct Node{   char data;   Node *next;   Node(char val)   {       data=val;       next=NULL;   }};public: string FirstNonRepeating(string A){     Node*temp=new Node('0'),*head1=temp;     string str="";     for(int i=0;i<A.length();i++)     {         temp=new Node(A[0]);         temp=temp->next;     }     while(temp!=NULL)     {         if(temp->data==temp->next->data)         temp->next->data='#';         temp=temp->next;     }     while(temp!=NULL)     {         str.push_back(temp->data);         temp=temp->next;     }     return str; }
}; 
0
deeptimayeemaharana06
This comment was deleted.
0
bhaskarmaheshwari81 week ago
 int arr[26]={0};     int repeated[26];     memset(repeated,-1,sizeof(repeated));           string ans;           int k=0;                      for(int i=0;str[i]!=0;i++)           {            arr[str[i]-'a']++;            int min1=27;            char ch;            if(arr[str[i]-'a']==1)            {                repeated[str[i]-'a']=k++;            }            else{                repeated[str[i]-'a']=27;            }            for(int j=0;j<26;j++)            {               if(repeated[j]!=-1&&repeated[j]<min1)               {                   min1=repeated[j];                   ch=j+'a';               }            }            if(min1==27)            {                ans.push_back('#');            }            else{                ans.push_back(ch);            }                        }           return ans;
+1
bhaskarmaheshwari81 week ago
TLE
O(n^2)
 
 int arr[26]={0};     string ans;     for(int i=0;str[i]!=0;i++)     {         arr[str[i]-'a']++;         bool flag=0;          for(int j=0;str[j]!=0;j++)          {              if(arr[str[j]-'a']==1)              {                  ans.push_back(str[j]);                  flag=1;                  break;              }          }          if(!flag)          ans.push_back('#');               }     return ans;
+1
narendrarokkam1452 weeks ago
class Solution{   public String FirstNonRepeating(String a)   {       int[] freq = new int[26];       StringBuilder ans = new StringBuilder();       Queue<Character> q = new LinkedList<>();       for(int i=0; i<a.length(); i++){               char ch = a.charAt(i);               freq[ch-'a']++;               q.offer(ch);               while(!q.isEmpty()){                   if(freq[q.peek()-'a']>1)                       q.poll();                   else{                       ans.append(q.peek());                       break;                   }               }               if(q.isEmpty())                   ans.append('#');       }       return ans.toString();   }}
0
ramsevak15242 weeks ago
// { Driver Code Starts#include<bits/stdc++.h>using namespace std;
// } Driver Code Endsclass Solution {public: string FirstNonRepeating(string s){     string ans="";     int mp[26];     int ind[26];      for(int i=0;i<26;i++)      {mp[i]=0;      ind[i]=0;      }     int c=1;     char ch=s[0];     mp[s[0]-97]=1;     ind[s[0]-97]=1;     ans+=s[0];    // cout<<mp[0];     for(int i=1;i<s.size();i++)     {         mp[s[i]-97]++;         c=mp[ch-97];         if(ind[s[i]-97]==0)         {             ind[s[i]-97]=i+1;         }        // cout<<c<<" ";         if(c>1)         {                         for(int j=0;j<26;j++)            {                if(mp[j]!=0)                {                    if(c==mp[j] && ind[j]<ind[ch-97])                    {                        ch=char(j+97);                    }                   else if(c>mp[j])                    {                        c=mp[j];                        ch=char(j+97);                    }                }            }         }         if(c==1)         {             ans+=ch;         }         if(c>1)         {             ans+='#';         }     }     //cout<<mp[1]<<" ";     return ans; }
};
// { Driver Code Starts.int main(){int tc;cin >> tc;while(tc--){ string A; cin >> A; Solution obj; string ans = obj.FirstNonRepeating(A); cout << ans << "\n";}return 0;}  // } Driver Code Ends
0
tthakare732 weeks ago
//java solution -> tc -> 6.28
//hint -> using HashSet and ArrayList
//also plese optimize my solution

class Solution{
    public String FirstNonRepeating(String A){
        String result = "";
        ArrayList<Character> adj = new ArrayList<>();
        HashSet<Character> set = new HashSet<>();
        
        char[] arr = A.toCharArray();
        for(int i = 0; i < arr.length; i++){
            if(!adj.contains(new Character(arr[i]))){
                //check if this element ever preset in arrayList by using hashset
                if(!set.contains(new Character(arr[i]))){
                    adj.add(new Character(arr[i]));
                    set.add(new Character(arr[i]));
                }
                if(adj.size() < 1) {
                    result += "#";
                } else {
                    result += adj.get(0);
                }
            } else {
                adj.remove(new Character(arr[i]));
                if(adj.size() < 1) {
                    result += "#";
                } else {
                    result += adj.get(0);
                }
            }
        }
        
        return result;
    }
}
0
msharma042 weeks ago
class Solution{   public String FirstNonRepeating(String str)   {       // code here              List<Character> DLL = new ArrayList<>(); String ans = ""; boolean[] repeat = new boolean[26];  for(int i=0;i<repeat.length;i++)  repeat[i] = false;
 for(int i=0;i<str.length();i++){    char x = str.charAt(i);
  if(!repeat[(int)(x - 'a')]){   // this character has occured less than 2 times
   if(!DLL.contains(x))    DLL.add(x);
   else{        DLL.remove((Character)x);
    repeat[(int)(x-'a')] = true;   }  }
  if(DLL.size() != 0){   char temp = DLL.get(0);          ans = ans + temp;           }    else      ans = ans + '#';       }  return ans;   }}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.