![]() |
VOOZH | about |
Given an array arr[] consisting of N strings and Q queries in form of two strings prefix and suffix, the task for each query is to find any one string in the given array with the given prefix and suffix. If there exists no such string then print "-1".
Examples:
Input: arr[] = {"apple", "app", "biscuit", "mouse", "orange", "bat", "microphone", "mine"}, Queries[] = {{a, e}, {a, p}}
Output:
apple
app
Explanation:
Query 1: String "apple" is the only word in the given dictionary with the given prefix "a" and suffix "e".
Query 2: String "app" is the only word in the given dictionary with the given prefix "a" and suffix "p".Input: arr[] = {"apple", "app", "biscuit", "mouse", "orange", "bat", "microphone", "mine"}, Queries[] = {{mi, ne}}
Output: mine
Naive Approach: The simplest approach to solve the given problem is to traverse the given array of strings arr[] for each query and if there exists any such string with the given prefix and suffix, then print that string. Otherwise, print "-1".
apple mine
Time Complexity: O(Q*N*M), where M is the maximum length of the string.
Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimized by using the Trie Data Structure to solve the problem. The implementation of trie can be modified to support both prefix and suffix search in the following way:
Follow the steps below to solve the problem:
Below is the implementation of the above approach:
apple mine
Time Complexity: O(N*M2 + Q*M), where M is the maximum length of among all the strings
Auxiliary Space: O(N*M2)