Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Trie

Search Suggestions

Medium · Trie · Asked at Amazon, Google, Microsoft, Flipkart

You have a list of distinct product names. A user types the word s one letter at a time. After each letter, print up to three product names that start with the typed prefix, in lexicographic order. If no product matches, print - for that letter.

Input

First line: n. Next n lines: one product name each. Last line: the word s.

Output

|s| lines — the suggestions after each typed letter, space-separated, or -.

Constraints

Insert all names into a trie, storing at each node the (at most three) smallest names passing through it — or sort the names and binary-search the first name ≥ prefix, then look at the next three.

Example 1

Input

5
mobile
mouse
moneypot
monitor
mousepad
mouse

Output

mobile moneypot monitor
mobile moneypot monitor
mouse mousepad
mouse mousepad
mouse mousepad

Example 2

Input

1
havana
tatiana

Output

-
-
-
-
-
-
-

Hints

  1. All the answers share the typed prefix — a trie groups words by prefix.
  2. If you insert the names in sorted order, the first three names that pass through a node are its three smallest.
  3. Once the typed prefix leaves the trie, every later prefix has no matches either.

Approach

Sort the names and insert them into a trie; at every node on a name's path, remember the name if the node has fewer than three stored. Then walk the trie with the typed letters: after each letter print the node's stored names, or "-" once the walk has fallen off the trie. Each letter costs O(1) to look up.

Complexity: O(L log n + total letters) time · O(total letters) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

struct TrieNode {
    int next[26];
    vector<int> top; // indices of up to 3 names, smallest first
    TrieNode() { memset(next, -1, sizeof next); }
};

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<string> names(n);
    for (auto &s : names) cin >> s;
    string word;
    cin >> word;
    sort(names.begin(), names.end());
    vector<TrieNode> t(1);
    for (int i = 0; i < n; i++) {
        int cur = 0;
        for (char c : names[i]) {
            int x = c - 'a';
            if (t[cur].next[x] == -1) {
                t[cur].next[x] = t.size();
                t.emplace_back();
            }
            cur = t[cur].next[x];
            if (t[cur].top.size() < 3) t[cur].top.push_back(i);
        }
    }
    int cur = 0;
    for (char c : word) {
        if (cur != -1) cur = t[cur].next[c - 'a'];
        if (cur == -1) {
            cout << "-\n";
            continue;
        }
        for (size_t j = 0; j < t[cur].top.size(); j++) cout << names[t[cur].top[j]] << (j + 1 < t[cur].top.size() ? ' ' : '\n');
    }
    return 0;
}

Python solution

import sys

data = sys.stdin.read().split()
n = int(data[0])
names = sorted(data[1 : 1 + n])
word = data[1 + n]
root = {}
for name in names:
    node = root
    for c in name:
        node = node.setdefault(c, {})
        top = node.setdefault("#", [])
        if len(top) < 3:
            top.append(name)
out = []
node = root
for c in word:
    node = node.get(c) if node is not None else None
    out.append(" ".join(node["#"]) if node else "-")
print("\n".join(out))

Java solution

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine().trim());
        String[] names = new String[n];
        for (int i = 0; i < n; i++) names[i] = br.readLine().trim();
        String word = br.readLine().trim();
        Arrays.sort(names);
        List<int[]> next = new ArrayList<>();
        List<List<Integer>> top = new ArrayList<>();
        next.add(new int[26]);
        Arrays.fill(next.get(0), -1);
        top.add(new ArrayList<>());
        for (int i = 0; i < n; i++) {
            int cur = 0;
            for (char c : names[i].toCharArray()) {
                int x = c - 'a';
                if (next.get(cur)[x] == -1) {
                    int[] fresh = new int[26];
                    Arrays.fill(fresh, -1);
                    next.add(fresh);
                    top.add(new ArrayList<>());
                    next.get(cur)[x] = next.size() - 1;
                }
                cur = next.get(cur)[x];
                if (top.get(cur).size() < 3) top.get(cur).add(i);
            }
        }
        StringBuilder sb = new StringBuilder();
        int cur = 0;
        for (char c : word.toCharArray()) {
            if (cur != -1) cur = next.get(cur)[c - 'a'];
            if (cur == -1) {
                sb.append("-\n");
                continue;
            }
            List<Integer> t = top.get(cur);
            for (int j = 0; j < t.size(); j++) sb.append(names[t.get(j)]).append(j + 1 < t.size() ? " " : "\n");
        }
        System.out.print(sb);
    }
}

Solve Search Suggestions online · All practice problems