Problem Summary
This is a classic streaming + queue + frequency problem.
Given a string s, for each index i, you must find:
Key Insight
We need:
So we use:
Idea
For each character:
Algorithm
For each character c:
Example
Input:
aabc
Step-by-step:
Prefix: a
Prefix: aa
Prefix: aab
Prefix: aabc
Output:
a#bb
Java Solution
import java.util.*;
class Solution {
public String firstNonRepeating(String s) {
int[] freq = new int[26];
Queue<Character> q = new LinkedList<>();
StringBuilder ans = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
// update frequency
freq[ch - 'a']++;
// add to queue
q.add(ch);
// remove all repeating characters from front
while (!q.isEmpty() && freq[q.peek() - 'a'] > 1) {
q.poll();
}
// append result
if (q.isEmpty()) {
ans.append('#');
} else {
ans.append(q.peek());
}
}
return ans.toString();
}
}
Complexity
Key Takeaways
Use queue for order
Use frequency array for repetition check
Classic streaming problem pattern
Very common in interviews (Amazon, Microsoft, Adobe)
Pattern Recognition
If you see:
Think:
Queue + Frequency Map
Summary
This problem demonstrates how to efficiently process a stream of characters by combining a queue for maintaining order and a frequency array for tracking repetition. By continuously updating both structures, we can determine the first non-repeating character at each step in linear time.