VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-first-non-repeating-character-stream-characters/

⇱ First Non Repeating Character - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

First Non Repeating Character

Last Updated : 16 Jun, 2026

Given a string s consisting of lowercase letters, for each position i in the string (0 ≤ i < n), find the first non-repeating character in the prefix s[0..i]. If no such character exists, use '#'.

Examples:

Input: s = "aabc"
Output: a#bb
Explanation:
After ("a"): First non-repeating character is 'a'.
After ("aa"): No non-repeating character, so '#'.
After ("a#b"): First non-repeating character is 'b'.
After ("aabc"): Non-repeating characters are 'b' and 'c'; 'b' appeared first, so 'b'.
Result = a#bb

Input: s = "bb"
Output: b#
Explanation:
After ("b"): First non-repeating character is 'b'.
After ("bb"): No non-repeating character, so '#'.
Result = b#

[Naive Approach] Using Nested Loop - O(n2) time and O(n) space

This approach maintains a frequency count of each character using a vector. For each character in the string, it scans from the beginning to find the first non-repeating character by checking the frequency of each character up to that point. If a non-repeating character is found, it is appended to the result; otherwise, # is appended when no such character exists. This process ensures that the first non-repeating character is identified at each step.


Output
a#bb

[Better Approach] Using Queue and Frequency Array - O(n) Time and O(n) Space

We use a count array of size 26 to track character frequencies and a queue to maintain their order of appearance. For each new character, we update its frequency and push it into the queue. Then, we remove characters from the front of the queue until the first non-repeating character is found, or the queue becomes empty.


Output
a#bb

[Expected Approach] Using Frequency and Last Occurrence Array- O(n) Time and O(1) Space

We maintain a frequency array to count occurrences and another array to store the first position of each character. While processing the string, we update frequencies and then check which character has frequency 1 and appeared earliest. That character becomes the current answer; if none exists, we place a '#'.


Output
a#bb
Comment