Search Suggestions System

Suggest up to three products after each typed letter, with a trie whose nodes keep their three smallest products.

Given a list of product names products and a word searchWord that is typed one letter at a time, return suggestions after each letter. After every letter, suggest up to three products that start with the letters typed so far, choosing the ones that come first in alphabetical order. If fewer than three products match, suggest all of them. The answer holds one list per letter of searchWord.

Example 1
Input: products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"
Output: [["mobile","moneypot","monitor"],["mobile","moneypot","monitor"],["mouse","mousepad"],["mouse","mousepad"],["mouse","mousepad"]]
Example 2
Input: products = ["havana"], searchWord = "tatiana"
Output: [[],[],[],[],[],[],[]]
Solution

The Idea

You have probably used a search box that offers a few suggestions while you type and changes them with every letter. In Example 1 the shop sells five products, mobile, mouse, moneypot, monitor and mousepad, and someone types mouse.

The letters typed so far, the beginning of the search word, are called a prefix. After the prefix m, all five products match, but only three may be shown: mobile, moneypot and monitor, the first three in alphabetical order. The prefix mo changes nothing. After mou only mouse and mousepad are left, and the last two letters keep those two.

Each new letter only adds to the prefix, so the products that match mou are some of the products that matched mo. Can the work for one letter build on the work for the letter before, instead of looking through every product again?

Write the five products as paths of letters that share their beginnings. All of them start with m and then o, so those two steps are written once. After mo the paths split three ways: b leads on to mobile, n to moneypot and monitor, and u to mouse and mousepad. Look at the picture below.

The trie of mobile, moneypot, monitor, mouse and mousepad, with letters on the links and teal circles where a product ends. The path m-o-u-s-e is highlighted in orange. Boxes underneath show the products stored on each node of that path: mobile, moneypot, monitor for typed m and mo, and mouse, mousepad for typed mou, mous and mouse.

The circle labelled root, on the left, stands for nothing typed yet. Each link carries one letter, and each circle stands for the letters on the way to it. A teal circle with a dot marks the end of a product: mouse ends on the circle after e, and mousepad carries on through p, a and d. A tree of letters like this one, where the five products share the circles of their common beginnings, is called a trie.

Typing mouse means following the orange path m-o-u-s-e, one link per letter. Every product whose path passes through a circle starts with that circle's letters. So the suggestions for a prefix are the three smallest products reachable from its circle.

If each circle keeps those three products in a list of its own, typing a letter costs one step along a link and one look at a list. The boxes along the bottom of the picture show the lists. The box labelled typed "mou" holds mouse and mousepad, which is the third answer of Example 1.

Solution Approach

The simple way looks through every product again after each letter. The trie avoids that once three things are settled: how a circle stores its links, how it keeps its three suggestions, and how the search word walks down.

Checking every product for every prefix

What does the simple way look like? After each letter, go through all the products, keep those that start with the prefix, sort them and take the first three. For Example 1 that means checking five products five times. With many products and a long search word, every letter repeats a full pass, even though the matches for mou are already among the matches for mo.

Storing the links of each node

How does a circle find the next circle for a letter? In the code a circle is a node, an object of a small class named Node. Each node has an array named next with 26 slots, one per letter from a to z. The slot for a letter ch is next[ch - 'a'], so a goes to slot 0, b to slot 1, and so on. A slot holding null means no product continues with that letter.

The products and search words in both examples use only lowercase letters a to z, and the 26 slots rely on that.

Keeping three suggestions on each node

Which three products should a node keep? The three smallest in alphabetical order among the products that pass through it. Sorting the products first makes that easy: Example 1 becomes mobile, moneypot, monitor, mouse, mousepad. Each product is then added, in that order, to the list of every node on its path, as long as the list, named top3, holds fewer than three products.

The first three products to reach a node are then the three smallest, and the list never needs sorting again. Without the sort, the node for m would keep the first three products in input order. Built from the unsorted array, it holds [mobile, mouse, moneypot], while the right answer is [mobile, moneypot, monitor].

Answering one letter at a time

How does typing turn into answers? A pointer named cur starts at the root. For each letter of the search word, cur moves to that letter's slot, and the answer for this prefix is the top3 list of the node it lands on.

If the slot is empty, cur becomes null. No product starts with these letters, so none can start with a longer prefix either, and every later letter gets an empty list. In Example 2 the root of the trie for havana has no link for t, so all seven answers for tatiana are empty.

Java Solution

The method suggestedProducts works in these steps:

  1. First, copy the products into sorted with products.clone(), and sort the copy with Arrays.sort(sorted). Sorting a copy leaves the caller's array in its original order.
  2. Create an empty node, root. The nested class Node holds the 26-slot array next and the list top3.
  3. Insert the products with two loops, one inside the other. The outer loop takes each product p from sorted and starts a pointer cur at root. The inner loop goes through the letters of p. For each letter it computes the slot i = ch - 'a' and creates a node there if the slot is empty. Then it moves cur to that node and adds p to its top3 if that list holds fewer than three products.
  4. Then walk the search word. A new list, result, will hold one answer per letter, and a new pointer cur starts at root again. For each letter, cur moves to the node in that letter's slot, or stays null once it is null. Then result gets that node's top3, or an empty list when cur is null.
  5. When every letter of the search word is done, return result.

A helper method, show, prints one line per prefix: the prefix, an arrow, and its suggestions. The main method runs Example 1 and prints the products array afterwards, runs Example 2, tries the search word "hx" against havana, and uses five products where more than three share a prefix.

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

public class SearchSuggestionsSystem {

    private static class Node {
        Node[] next = new Node[26];                  // one slot per letter a to z
        List<String> top3 = new ArrayList<>();       // smallest 3 products with this prefix
    }

    public List<List<String>> suggestedProducts(String[] products, String searchWord) {
        String[] sorted = products.clone();
        Arrays.sort(sorted);              // sorted order fills each top3 with the smallest
        Node root = new Node();
        for (String p : sorted) {
            Node cur = root;
            for (char ch : p.toCharArray()) {
                int i = ch - 'a';
                if (cur.next[i] == null) {
                    cur.next[i] = new Node();
                }
                cur = cur.next[i];
                if (cur.top3.size() < 3) {
                    cur.top3.add(p);
                }
            }
        }

        List<List<String>> result = new ArrayList<>();
        Node cur = root;
        for (char ch : searchWord.toCharArray()) {
            cur = cur == null ? null : cur.next[ch - 'a'];  // a broken path stays broken
            result.add(cur == null ? new ArrayList<>() : cur.top3);
        }
        return result;
    }

    static void show(String searchWord, List<List<String>> lists) {
        for (int k = 0; k < lists.size(); k++) {
            System.out.println(searchWord.substring(0, k + 1) + " -> " + lists.get(k));
        }
    }

    public static void main(String[] args) {
        SearchSuggestionsSystem s = new SearchSuggestionsSystem();
        String[] products = {"mobile", "mouse", "moneypot", "monitor", "mousepad"};
        show("mouse", s.suggestedProducts(products, "mouse"));
        System.out.println(Arrays.toString(products));    // the caller's array is unchanged
        System.out.println(s.suggestedProducts(new String[] {"havana"}, "tatiana"));
        System.out.println(s.suggestedProducts(new String[] {"havana"}, "hx"));
        String[] more = {"bags", "baggage", "banner", "box", "cloths"};
        show("bags", s.suggestedProducts(more, "bags"));
    }
}

Running it prints:

Output
m -> [mobile, moneypot, monitor]
mo -> [mobile, moneypot, monitor]
mou -> [mouse, mousepad]
mous -> [mouse, mousepad]
mouse -> [mouse, mousepad]
[mobile, mouse, moneypot, monitor, mousepad]
[[], [], [], [], [], [], []]
[[havana], []]
b -> [baggage, bags, banner]
ba -> [baggage, bags, banner]
bag -> [baggage, bags]
bags -> [bags]

Look at the lines m -> and mo ->: both suggest [mobile, moneypot, monitor]. The product mouse comes second in the input and starts with m as well, but sorting put it fourth, too late for the list. From mou -> on, only mouse and mousepad remain. The next line, [mobile, mouse, moneypot, monitor, mousepad], is the products array after the call, still in the caller's order, because only the copy was sorted.

For tatiana, all seven lists are empty. The line [[havana], []] shows a path that breaks in the middle: h leads to havana, but havana has an a after its h, not an x, so the second list is empty.

The last four lines show the limit of three. Four products start with b: bags, baggage, banner and box. The node for b keeps [baggage, bags, banner], and box, fourth in sorted order, is left out. Typing a, g and s then narrows the list down to [bags].

Complexity

The work is the sort, one step per letter of every product to build the trie, and one step per letter of the search word. Here N is the number of products, L the length of the longest product, and S the length of the search word.

  • Time: O(L × N log N + S), because the sort makes about N log N comparisons of up to L letters each, while building the trie and walking the search word take one step per letter.
  • Space: O(N × L), because each letter of a product creates at most one node, and every node carries 26 slots and a list of at most three references to products.

The plain trie, with insert and search but no stored lists, is built in Implement Trie.