Auto-Complete

Interview

Time limit1sMemory limit128 MB

Summary
The app prints the original index of the K-th dictionary word with each query prefix in alphabetical order, or -1.
Level

Medium4 of 10

Topics
Trie, Sorting
Solved
No attempts yet

Problem

Bessie the cow has a new phone and likes sending text messages, but her hooves are large and the screen is small, so she misspells a lot of words. Farmer John agreed to help by writing an auto-complete app that takes the front part of a word and fills in the rest.

The app reads one dictionary. It holds WW words, each made only of the lowercase letters a to z, and the letters of all dictionary words add up to at most 1,000,000.

The app answers NN queries (1≤N≤100001 \le N \le 10000). One query is a partial word together with an integer KiK_i. A partial word is also made only of lowercase letters and its length is between 1 and 1,000, and KiK_i is a positive integer. For query ii, the app collects every dictionary word that has the iith partial word as a prefix, puts those words in alphabetical order, and takes the KiK_ith of them. Call that word the KiK_ith completion of the iith partial word.

Input

The first line contains the integers WW and NN.

Each of the next WW lines contains one dictionary word. The word written on the iith of these lines is the iith word of the dictionary.

Each of the next NN lines contains an integer KiK_i and a partial word, separated by one space.

Output

Print NN lines. Line ii holds the position in the dictionary, an integer between 1 and WW, of the KiK_ith completion of the iith partial word. If that partial word has fewer than KiK_i completions, print -1 instead.

If the same word sits in the dictionary more than once, alphabetical order alone does not separate the copies. In that case the copy that comes earlier in the dictionary counts as the earlier completion.

Hint

In the first example the completions of a are aa, aaa, aab, ab, abc, ac. The fourth completion is ab, on line 3 of the dictionary. The completions of da are daa, dab, dadba, so the second completion is dab, on line 1 of the dictionary. da has only three completions, so it has no fourth one.

Examples1

  1. Example 1

    Input
    10 3
    dab
    ba
    ab
    daa
    aa
    aaa
    aab
    abc
    ac
    dadba
    4 a
    2 da
    4 da
    
    Expected output
    3
    1
    -1