![]() |
VOOZH | about |
Given two arrays of strings containing words[] and queries[] having N and Q strings respectively, the task is to find the number of strings from words[] having queries[i] as the prefix for all the strings in queries[].
Examples:
Input: words[] = { "geeks", "geeks", "geeks for geeks", "string", "strong" }, queries[] = { "geek", "gel", "str" }
Output: 3, 0, 2
Explanation:
1st query "geek" is present in 3 words in the list as a prefix, { "f", "s", "" }
2nd query "gel" is not present in any word in the list as a prefix
3rd query "str" is present in 2 words in the list as a prefix, {"ing", "ong"}Input: words[] = { "apple", "app", "ape", "alien", "a", "box", "boxing" }, queries[] = { "a", "ap", "b", "app", "book" }
Output: 5, 3, 2, 2, 0
Explanation:
1st query "a" is present in 5 words in the list as a prefix, { "pple", "pp", "pe", "lien", "" }
2nd query "ap" is present in 3 words in the list as a prefix, { "ple", "p", "e" }
3rd query "b" is present in 2 words in the list as a prefix, {"ox", "oxing"}
4th query "app" is present in 2 words in the list as a prefix, {"le", ""}
5th query "book" is not present in any word in the list as a prefix
Naive Approach: The problem can be solved based on the following idea:
For each query traverse through every word in the list and check whether the word has a prefix as current query or not.
Below is the implementation of the above approach.
3 0 2
Time Complexity: O(N * Q * M), where M = maximum length of a string in queries[]
Auxiliary Space: O(N)
Efficient approach: The problem can be solved efficiently on the basis of the following approach
We have to use such a data structure to match the string to find out if it is prefix of another string in optimal time. Trie can help us in this problem.
Build a trie and insert the strings of word[] in the trie. where each node will also keep a count of strings with that prefix. Then while traversing through queries[] find the prefix and the count associated with it. The structure of a trie node will be like the following:
- children: This field is used for mapping from a character to the next level trie node
- isEndOfWord: This field is used to distinguish the node as end of word node
- num: This field is used to count the number of times a node is visited during insertion in trie
Follow the steps mentioned below to implement the idea:
Below is the implementation of the above approach:
3 0 2
Time Complexity: O(Q * x + N*L), Where x is the longest word in the query, and L = length of the longest word inserted in the trie.
Auxiliary Space: O(N * List [i])