Prefix Suffix Search
Time limit3sMemory limit512 MB
Given N words and Q prefix/suffix pairs, report for each query how many words match both prefix and suffix. Total input length is up to 2.5 million.
- Level
Hard8 of 10
- Topics
- String matching, Trie, Hash map, Divide and conquer
- Solved
- No attempts yet
Problem
As an English learner, sometimes you cannot remember the entire spelling of an English word perfectly, and you can only remember its prefix and suffix. For example, you may want to use a word that begins with appr and ends with iate, but forget the middle part. It may be appreciate, appropriate, or something like them.
With an ordinary dictionary you can look up words beginning with a certain prefix, but filtering words that end with a certain suffix as well is inconvenient. So dictionary functionality that finds words having a given prefix and suffix is helpful. To start, let us count the number of such words instead of listing them all.
More formally, you are given a list of words. Then you are given queries, each consisting of two strings. Write a program that outputs, for each query, the number of words in the given list that have both the given prefix and the given suffix.
Input
The input consists of a single test case in the following format.
$N$ $Q$
$w_1$
...
$w_N$
$p_1$ $s_1$
...
$p_Q$ $s_Q$
The first line contains two integers and , where () is the number of words in the list and () is the number of queries. The -th of the following lines contains a string . The -th of the following lines contains two strings and , which are the prefix and suffix of the words to be searched for.
You can assume the following.
- All strings in the input are non-empty and consist only of lowercase English letters.
- The total length of the input strings does not exceed .
- The words in the given list are unique: if .
- The pairs of a prefix and a suffix are unique: if .
Output
For each query, output the number of words in the given list that have the given prefix and suffix, one per line.