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 productssearchWordsearchWord
Example 1
Output: [["mobile","moneypot","monitor"],["mobile","moneypot","monitor"],["mouse","mousepad"],["mouse","mousepad"],["mouse","mousepad"]]
Example 2
Output: [[],[],[],[],[],[],[]]
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 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 Nodenextchnext[ch - 'a']null
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
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 curcurtop3
If the slot is empty, curnull
Java Solution
The method suggestedProducts
- First, copy the products into
withsorted , and sort the copy withproducts.clone() . Sorting a copy leaves the caller's array in its original order.Arrays.sort(sorted) - Create an empty node,
. The nested classroot holds the 26-slot arrayNode and the listnext .top3 - Insert the products with two loops, one inside the other. The outer loop takes each product
fromp and starts a pointersorted atcur . The inner loop goes through the letters ofroot . For each letter it computes the slotp and creates a node there if the slot is empty. Then it movesi = ch - 'a' to that node and addscur to itsp if that list holds fewer than three products.top3 - Then walk the search word. A new list,
, will hold one answer per letter, and a new pointerresult starts atcur again. For each letter,root moves to the node in that letter's slot, or stayscur once it isnull . Thennull gets that node'sresult , or an empty list whentop3 iscur .null - When every letter of the search word is done, return
.result
A helper method, showmain
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:
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 ->mo ->[mobile, moneypot, monitor]mou ->[mobile, mouse, moneypot, monitor, mousepad]
For tatiana, all seven lists are empty. The line [[havana], []]
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][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