Queue based approach or first non-repeating character in a stream
Pattern: Implementation
Count each character as it arrives and add it to a queue. Then remove from the front while the front has been seen more than once. The front, if any, is the first non-repeating character so far; otherwise the answer for that step is #.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Characters (lowercase letters) arrive one at a time. After each one, record the first character so far that has
appeared exactly once, or # if there is none. Return all the answers as one string. "aabc" gives "a#bb".
The catalogue has no practice link for this one. The guide's Find the First Non-Repeating Character from a Stream page solves the same task, also with counting.
Think first
- What makes a character drop out of the running?
- Once a character repeats, can it ever be the answer again?
- Which structure keeps characters in arrival order?
Hints
Brute force, and why it fails
After each character, scan everything read so far for the first with count 1: O(n²).
The key insight
Each character enters the queue once and leaves at most once, and the front is always the oldest still-single character, so each step costs O(1) on average.
Dry run
| queue | a |
|---|---|
| out | a |
Stream "aabc". Read a: count a = 1, queue a. Answer a.
The plan
for c in stream:
count[c] += 1; queue.add(c)
while queue and count[queue.front] > 1: queue.remove_front()
append (queue.front if queue else '#')
Complexity
- Time
O(n)- Space
O(n)
Each character is added and removed once; the counts take 26 slots.
Edge cases
- All the same letter:
a#…#. - All different: each answer is the first letter.
- One character.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public String firstNonRepeating(String stream) {
int[] count = new int[26];
Queue<Character> q = new ArrayDeque<>(); // candidates, oldest first
StringBuilder out = new StringBuilder();
for (char c : stream.toCharArray()) {
count[c - 'a']++;
q.add(c);
while (!q.isEmpty() && count[q.peek() - 'a'] > 1) q.poll(); // drop fronts that have repeated
out.append(q.isEmpty() ? '#' : q.peek());
}
return out.toString();
}
}C++
class Solution {
public:
string firstNonRepeating(string stream) {
int count[26] = {0};
queue<char> q; // candidates, oldest first
string out;
for (char c : stream) {
count[c - 'a']++;
q.push(c);
while (!q.empty() && count[q.front() - 'a'] > 1) q.pop(); // drop fronts that have repeated
out += q.empty() ? '#' : q.front();
}
return out;
}
};Python
from collections import deque
class Solution:
def firstNonRepeating(self, stream: str) -> str:
count = [0] * 26
q = deque() # candidates, oldest first
out = []
for c in stream:
count[ord(c) - 97] += 1
q.append(c)
while q and count[ord(q[0]) - 97] > 1:
q.popleft() # drop fronts that have repeated
out.append(q[0] if q else "#")
return "".join(out)Common mistakes
- Removing only the front once instead of in a loop.
- Removing a repeated character from the middle of the queue: it is enough to skip it when it reaches the front.