Skip to content

Latest commit

 

History

History
47 lines (30 loc) · 697 Bytes

File metadata and controls

47 lines (30 loc) · 697 Bytes

First Non-Repeating Character in Stream

Problem Link

Practice Problem


Pattern

  • Queue
  • Hash Table

Approach

Maintain character frequencies and a queue of candidates, removing repeated characters from the front.


Time Complexity

O(n)

Space Complexity

O(1)


Java Solution

import java.util.*;
class FirstNonRepeatingStream {
    private int[] count = new int[26];
    private Queue<Character> queue = new LinkedList<>();

    public char add(char c) {
        count[c - 'a']++;
        queue.offer(c);
        while (!queue.isEmpty() && count[queue.peek() - 'a'] > 1) queue.poll();
        return queue.isEmpty() ? '#' : queue.peek();
    }
}