Stream of Characters

After each new letter, tell whether the letters received so far end with one of the given words.

Write a class StreamChecker that is built from a list of lowercase words and has a method query(letter). Letters arrive one at a time, one per call to query. After each letter, return true if the letters received so far end with some word from the list, and false otherwise.

Example 1
Input: StreamChecker(["cd", "f", "kl"]), then query a, b, c, d, e, f, g, h, i, j, k, l
Output: false, false, false, true, false, true, false, false, false, false, false, true
Explanation: after d the letters end in "cd", after f in "f", and after l in "kl".
Solution

The Idea

Picture someone typing into a chat box while a filter watches for a few words. The filter does not wait for the message to be finished. After every key press it asks: do the letters typed so far end with one of the words it is watching for?

Example 1 watches for "cd", "f" and "kl", and the letters a to l arrive in order. After a, b and c the stream of letters is "abc", which ends with none of the three words. Then d arrives, the stream is "abcd", and its last two letters are "cd", so that query returns true. Later f matches on its own, and l completes "kl".

Notice where every match sits: at the very end of the stream, finishing with the letter that just arrived. A word that ended earlier was already reported by an earlier query. So each query really asks one thing: does some word end exactly at the newest letter?

To answer that, read the stream backwards, starting from the newest letter. After d arrives, reading backwards gives d, then c, then b, then a. The word "cd" read from its last letter to its first also gives d, then c. So it pays to store every word reversed: "cd" as d then c, and "kl" as l then k.

Look at the picture below. On the right, the three reversed words hang from one starting point, labelled root. Each circle is called a node, and each link between two nodes carries one letter. Following the links d and c from the root spells "cd" backwards and reaches the teal node marked "cd", where that word ends.

The stream a, b, c, d is read backwards from the newest letter d. The trie holds the words cd, f and kl reversed: from the root, links d then c reach the end of cd, link f reaches f, and links l then k reach kl. The path d, c is highlighted.

A tree of letter links like this one is called a trie. Words whose stored letters begin the same way share their first links. If the list also held "bcd", its reversed letters d, c, b would follow the same d and c links and add one more link, b.

On the left of the picture is the stream after query d. Reading it backwards gives d, then c, and the orange path in the trie follows the same two letters, from the root to the teal node "cd". So query d returns true. For query c, the newest letter is c, the root has no link c, so the walk stops at once and the answer is false.

Solution Approach

The plain way compares every word with the end of the stream. The trie does better once three things are settled: how the words are stored, how a query walks the trie, and how far back a query reads.

Comparing every word with the end of the stream

Why not simply check each word after each letter? Each query would then compare the last letters of the stream with every word in the list, which costs up to the total number of letters in all the words. Most of that work is wasted. After query b in Example 1, no word ends with b, yet all three words are still compared. The trie rules them all out with one missing link at the root.

Storing the words reversed

How does a word get into the trie? Start at the root and take the word's letters from last to first. For each letter, follow the link with that letter, or create it if it is missing. After the word's first letter, which comes last in this order, mark the node the walk stopped at as a word end.

Why does the order matter so much? If the words were stored forward, a backward walk would compare letters in opposite orders. With the word "ab" and the stream "ba", reading backwards gives a, then b, which spells "ab" forward, so the second query would wrongly return true.

Walking the trie from the newest letter

What does one query do? It adds the letter to the end of the stream, then reads the stream backwards from that letter, stepping down one link of the trie for each letter it reads. A missing link means no word ends with the letters read so far, so the answer is false. A node marked as a word end means a word ends at the newest letter, so the answer is true at once.

Stopping at the first word end is safe, because the question is whether some word matches, not which one. With the words "cd" and "bcd" and the stream "bcd", the walk reaches the end of "cd" after two letters and returns true there.

How far back to read

How long can one walk get? The stream keeps growing, but a word that ends at the newest letter starts at most as many letters back as the longest word has. So the checker remembers that length and never reads further back. In Example 1 the longest words have two letters, so even the twelfth query reads only l and k.

The stream itself still keeps every letter. As an optional improvement, an array with one slot per letter of the longest word could hold just the last few letters, each new letter overwriting the oldest one. The code below keeps the whole stream, which is simpler to read.

Java Solution

The class has five parts, one for each piece of the approach:

  • Node: one node of the trie, with next, an array of 26 links where index 0 is a and index 25 is z, and isWord, true where a stored word ends.
  • root: the starting node of the trie.
  • The constructor: inserts each word reversed and keeps the length of the longest word in maxLen.
  • stream: a StringBuilder holding every letter received so far.
  • query: appends the letter, then walks the trie backwards from it, reading at most maxLen letters.

A small helper, run, builds a checker, sends it the letters one by one and prints the answers as a list. The main method uses it for Example 1, for two words that overlap in the stream "aba", for the word "ab" against the stream "ba", and for the words "cd" and "bcd" against "bcd".

Java
import java.util.ArrayList;
import java.util.List;

public class StreamChecker {

    private static class Node {
        Node[] next = new Node[26];      // one link per letter a to z
        boolean isWord;                  // a word ends here
    }

    private final Node root = new Node();
    private final StringBuilder stream = new StringBuilder();
    private int maxLen = 0;

    public StreamChecker(String[] words) {
        for (String w : words) {
            maxLen = Math.max(maxLen, w.length());
            Node cur = root;
            for (int i = w.length() - 1; i >= 0; i--) {     // insert each word reversed
                int c = w.charAt(i) - 'a';
                if (cur.next[c] == null) {
                    cur.next[c] = new Node();
                }
                cur = cur.next[c];
            }
            cur.isWord = true;
        }
    }

    public boolean query(char letter) {
        stream.append(letter);
        Node cur = root;
        // read the stream backwards from the newest letter, at most maxLen letters
        for (int i = stream.length() - 1; i >= 0 && i >= stream.length() - maxLen; i--) {
            cur = cur.next[stream.charAt(i) - 'a'];
            if (cur == null) {
                return false;            // no word ends with these letters
            }
            if (cur.isWord) {
                return true;             // a word ends at the newest letter
            }
        }
        return false;
    }

    static void run(String[] words, String letters) {
        StreamChecker checker = new StreamChecker(words);
        List<Boolean> answers = new ArrayList<>();
        for (char c : letters.toCharArray()) {
            answers.add(checker.query(c));
        }
        System.out.println(letters + " -> " + answers);
    }

    public static void main(String[] args) {
        run(new String[] {"cd", "f", "kl"}, "abcdefghijkl");
        run(new String[] {"ab", "ba"}, "aba");
        run(new String[] {"ab"}, "ba");
        run(new String[] {"cd", "bcd"}, "bcd");
    }
}

Running it prints:

Output
abcdefghijkl -> [false, false, false, true, false, true, false, false, false, false, false, true]
aba -> [false, true, true]
ba -> [false, false]
bcd -> [false, false, true]

Look at the line for abcdefghijkl: true appears in the fourth, sixth and twelfth places, after d, f and l, just as Example 1 expects. In aba -> [false, true, true], the b in the middle belongs to two matches. The word "ab" ends at it, and the word "ba" starts with it and ends at the last a.

The line ba -> [false, false] shows why the words go in reversed. The stream holds the letters of "ab", but in the wrong order, so no word ends there. The same class with the words stored forward prints [false, true] for this stream, and for Example 1 it misses the matches at d and l.

The last line comes from the words "cd" and "bcd". Its third query reaches the teal end of "cd" after reading d and c, and returns true before it ever looks at the b.

Complexity

Building the checker handles each letter of each word once, and each query walks at most maxLen links of the trie.

  • Time to build: O(total letters in the words), because the constructor follows or creates exactly one link for every letter of every word.
  • Time per query: O(maxLen), because the walk reads at most maxLen letters back with one array lookup each, and appending to the StringBuilder takes constant time on average.
  • Space: O(26 × total letters in the words) plus one character per query, because every stored letter can add one node with 26 links, and stream keeps every letter received.

For building and searching a trie with words stored forward, see Implement Trie.