Find the first non-repeating character from a stream of characters

Pattern: Hashing and frequency

medium

After each new character, report the earliest character seen exactly once so far, using counts and a queue of candidates in arrival order.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

You are given a stream of lowercase letters as a string. After each letter arrives, write down the earliest letter so far that has appeared exactly once, or # if there is none. Return the written characters as a string. For example, the stream "aabc" gives "a#bb".

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name firstNonRepeating and the # convention are this guide's own.

Think first

  • After "aab", which letters have appeared exactly once? Which of them came first?
  • Once a letter has repeated, can it ever be the answer again?
  • What structure keeps letters in arrival order and lets you drop old ones from the front?

Hints

    Brute force, and why it fails

    After each new letter, rescan everything seen so far for the first letter with count 1. That is O(n) per step and O(n²) in total. Since there are only 26 letters, scanning the 26 letters in arrival order also works, but the queue makes each step O(1) on average.

    The key insight

    A letter that repeats is out for good. So the candidates can wait in a queue in arrival order, and repeated ones are removed from the front lazily, only when they reach it.

    Dry run

    a0 
    a1 
    b2 
    c3 
    queue[]
    out

    The stream is aabc. counts says how often each letter has appeared. The queue holds letters seen once, oldest first.

    Step 1 of 5

    The plan

    count = [0] * 26
    queue = empty queue
    out = ""
    for ch in stream:
        count[ch] = count[ch] + 1
        if count[ch] == 1:
            add ch to the back of queue
        while queue is not empty and count[front of queue] > 1:
            remove the front of queue
        append (front of queue, or '#') to out
    return out
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    Each letter enters the queue at most once and leaves at most once. The counts and the queue hold at most 26 letters, plus the output string that is returned.

    Edge cases

    • One letter: the output is that letter.
    • "zz" gives "z#".
    • A letter that repeats while it is not at the front stays in the queue until it reaches the front, and is removed then.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public String firstNonRepeating(String stream) {
            int[] count = new int[26];
            Deque<Character> candidates = new ArrayDeque<>();   // characters seen once, in arrival order
            StringBuilder out = new StringBuilder();
            for (char ch : stream.toCharArray()) {
                count[ch - 'a']++;
                if (count[ch - 'a'] == 1) {
                    candidates.addLast(ch);
                }
                while (!candidates.isEmpty() && count[candidates.peekFirst() - 'a'] > 1) {
                    candidates.pollFirst();                     // it has repeated: never an answer again
                }
                out.append(candidates.isEmpty() ? '#' : candidates.peekFirst());
            }
            return out.toString();
        }
    }

    C++

    class Solution {
    public:
        string firstNonRepeating(string stream) {
            int count[26] = {0};
            deque<char> candidates;                             // characters seen once, in arrival order
            string out;
            for (char ch : stream) {
                count[ch - 'a']++;
                if (count[ch - 'a'] == 1) {
                    candidates.push_back(ch);
                }
                while (!candidates.empty() && count[candidates.front() - 'a'] > 1) {
                    candidates.pop_front();                     // it has repeated: never an answer again
                }
                out.push_back(candidates.empty() ? '#' : candidates.front());
            }
            return out;
        }
    };

    Python

    class Solution:
        def firstNonRepeating(self, stream):
            from collections import deque
            count = [0] * 26
            candidates = deque()                    # characters seen once, in arrival order
            out = []
            for ch in stream:
                count[ord(ch) - ord("a")] += 1
                if count[ord(ch) - ord("a")] == 1:
                    candidates.append(ch)
                while candidates and count[ord(candidates[0]) - ord("a")] > 1:
                    candidates.popleft()            # it has repeated: never an answer again
                out.append(candidates[0] if candidates else "#")
            return "".join(out)

    Common mistakes

    • Adding a letter to the queue every time it arrives, instead of only on its first arrival.
    • Removing only one stale letter from the front, when several may have repeated.
    • Rescanning the whole stream at every step.

    Similar problems