Search Suggestions System

Medium Tries Basics

Search Suggestions System is a medium tries problem solved with the basics pattern. The best approach, optimal (trie with three suggestions per node), runs in O(n log n · L + S + m) time and O(S) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from sort, then scan for each prefix up.

Problem

You are given an array of distinct product names products and a string searchWord, all made of lowercase letters. Imagine typing searchWord into a search box one character at a time. After each character, the box shows at most three product names that start with the text typed so far. When more than three products match, it shows the three that come first in lexicographic order.

Return a list with one entry per character of searchWord: the entry for the i-th character is the list of suggestions shown once the first i characters have been typed (an empty list if nothing matches).

Examples

Example 1

Input
products = ["melon", "mango", "map", "maple", "mat", "milk"], searchWord = "map"
Output
[["mango", "map", "maple"], ["mango", "map", "maple"], ["map", "maple"]]
Why
In sorted order the products are mango, map, maple, mat, melon, milk. All six start with "m" and four start with "ma"; each time the first three are kept. Only map and maple start with "map".

Example 2

Input
products = ["ruby", "rust", "rose"], searchWord = "rot"
Output
[["rose", "ruby", "rust"], ["rose"], []]
Why
Every product starts with "r", only rose starts with "ro", and nothing starts with "rot", so the last list is empty.

Example 3

Input
products = ["kiwi"], searchWord = "fig"
Output
[[], [], []]
Why
No product starts with "f", so no longer prefix can match either. There is still one (empty) list per typed character.

Constraints

  • 1 <= products.length <= 1000
  • 1 <= products[i].length <= 3000
  • 1 <= sum(products[i].length) <= 2 * 10^4
  • All strings in products are distinct.
  • 1 <= searchWord.length <= 1000
  • products[i] and searchWord consist of lowercase English letters.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 14 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Sort, then scan for each prefixO(n log n · L + m · n · m)O(m)
Sort + binary searchO(n log n · L + m · (m log n))O(m)
Optimal (trie with three suggestions per node)O(n log n · L + S + m)O(S)

1Sort, then scan for each prefix

TimeO(n log n · L + m · n · m)Sorting compares strings of length up to L. Then, for each of the m prefixes, up to n products are checked, each check costing up to m character comparisons.
SpaceO(m)Apart from the output, only the current prefix is stored.

Sort the products so that any group of matches comes out in lexicographic order. For each prefix of the search word, scan the sorted list from the start and collect the first three products that begin with that prefix.

  1. Sort products.
  2. For each length 1..m, take prefix = searchWord[0..len).
  3. Scan the sorted products and add each one that starts with prefix, stopping after three.
  4. Append the list (possibly empty) to the result.
class Solution {
    public List<List<String>> suggestedProducts(String[] products, String searchWord) {
        Arrays.sort(products);
        List<List<String>> result = new ArrayList<>();
        for (int len = 1; len <= searchWord.length(); len++) {
            String prefix = searchWord.substring(0, len);
            List<String> list = new ArrayList<>();
            for (String p : products) {
                if (p.startsWith(prefix)) {
                    list.add(p);
                    if (list.size() == 3) break;
                }
            }
            result.add(list);
        }
        return result;
    }
}

3Optimal (trie with three suggestions per node)

TimeO(n log n · L + S + m)Sorting dominates. Building the trie touches each of the S characters once, and the walk is one step per character of the search word.
SpaceO(S)Up to S trie nodes (S = total length of all products), each holding at most three references.

Insert the sorted products into a trie. Because they arrive in lexicographic order, the first three words that pass through a node are exactly the three smallest words with that node's prefix, so each node simply keeps the first three it sees. Then walk the search word down the trie and read each node's list; once the walk falls off the trie, every remaining list is empty.

  1. Sort products.
  2. Insert each product; at every node on its path, append the product if the node holds fewer than three.
  3. Walk the search word from the root, one character per step.
  4. While the node exists, its list is the answer for this prefix; after a missing child, append empty lists.
class Solution {
    private static class Node {
        Node[] next = new Node[26];
        List<String> top = new ArrayList<>();
    }

    public List<List<String>> suggestedProducts(String[] products, String searchWord) {
        Arrays.sort(products);
        Node root = new Node();
        for (String p : products) {
            Node cur = root;
            for (char c : p.toCharArray()) {
                int i = c - 'a';
                if (cur.next[i] == null) cur.next[i] = new Node();
                cur = cur.next[i];
                if (cur.top.size() < 3) cur.top.add(p);
            }
        }
        List<List<String>> result = new ArrayList<>();
        Node cur = root;
        for (char c : searchWord.toCharArray()) {
            if (cur != null) cur = cur.next[c - 'a'];
            result.add(cur == null ? new ArrayList<>() : cur.top);
        }
        return result;
    }
}

Edge cases to test

  • No product matches even the first letter (every list is empty)
  • Matches stop part way through the search word (the remaining lists are empty)
  • Fewer than three products share a prefix
  • A product equal to a prefix sorts before its longer extensions
  • The search word is longer than every product
  • The input array is not sorted

Hints

Hint 1

Sort the products first. Then the products sharing any prefix form one contiguous block, already in lexicographic order.

Hint 2

For a prefix, binary search for the first product that is not smaller than it; the suggestions are at most the next three products, as long as they still start with the prefix.

Hint 3

Alternatively, build a trie from the sorted products and let every node keep the first three words that pass through it.

FAQ

What is the best time complexity for Search Suggestions System?

Optimal (trie with three suggestions per node) runs in O(n log n · L + S + m) time and O(S) extra space. Sorting dominates. Building the trie touches each of the S characters once, and the walk is one step per character of the search word.

Which pattern does Search Suggestions System use?

It is a tries problem that uses the basics pattern. Other problems with the same pattern: Implement Trie (Prefix Tree), Implement Trie ll, Design In-Memory File System.

Is there a brute force solution for Search Suggestions System?

Yes. Sort, then scan for each prefix takes O(n log n · L + m · n · m) time and O(m) space. Sort the products so that any group of matches comes out in lexicographic order.

Which edge cases should I test for Search Suggestions System?

No product matches even the first letter (every list is empty); Matches stop part way through the search word (the remaining lists are empty); Fewer than three products share a prefix; A product equal to a prefix sorts before its longer extensions; The search word is longer than every product; The input array is not sorted.