Problem LinkAuthor: Jitender Tester: Misha Chorniy Editorialist: Bhuvnesh Jain DifficultyEASYMEDIUM PrerequisitesTries, Offline querying ProblemYou a given $N$ strings and $Q$ queries. For each query, given $R$ and string $P$, you need to find the lexicographically smallest string which has the largest common prefix with $S$. ExplanationSubtask 1: N, Q ≤ 1000A simple brute force which checks each string from index $1$ to $R$ and stores the answer at each step will suffice. Below is a pseudocode for it:
The complexity of the above approach is $O(N * Q * 10)$ in the worst case as the maximum size of the string can be at most 10. Subtask 2: N, Q ≤ 100000The first idea which comes whenever you see string problems deal with prefixes if using tries or hashing. In this problem too, we will use trie for solving the problem. In case you don't know about it, you can read it here. Let us first try to understand how to find the lexicographically smallest string with largest common prefix with $P$. Assume we have the trie of all the strings build with us. We just start traversing the Trie from the root, one level at a time. Say we are at level $i$, we will try to greedily go to the node whose character matches with our current character, $P[i]$. This will help us to maximise the longest common prefix. The moment we find a mismatch, i.e. a node with current character doesn't exist, we will try to now greedily find the lexicographically find the smallest string. For this, we just keep on traversing down the leftmost node in the trie till a complete work is found. But the above approach works when $R = N$ in all queries as without it we can't identify whether the string we are traversing lies in the required range of the query or not. There are 2 different approaches to the full solution, Online solution and Offline solution. Author/Tester Solution: Offline ApproachThe problems where we can easily solve a problem given a full array but need to query for a prefix of the array can be easily handled using offline queries. The idea is as follows: We first sort the queries based on the index of the array given. We now build out data structure (here trie), incrementally. Say the data structure is built using all the first $i$ elements, we now answer every query which has an index as $i$ in the query. The pseudocode for it is below:
For more details, you can refer to the author's or tester's solution below. Editorialist Solution: Online SolutionThe idea is simple. With every node in the trie, we keep a vector of indices which it is a part of. Using this vector we can easily decide whether the string we are traversing lies within our required range or not. But before discussing the full solution, we need to be sure that this will fit into memory limits because seeing it in a naive manner seems to consume quadratic memory as each node can have a vector of length $N$. To prove that the abovemodified trie also uses linear memory in order of sum of the length of strings, we see that each index appears in any vector of a node in trie as many characters are there in the string. So, out trie just uses twice the memory that the normal trie (the one in author or tester solution) uses. Once, the above modified Trie is built, we can answer our queries easily. Since the strings are added incrementally, we are sure that the vector containing the indices will always be in sorted order. To check whether any string at a given node lies in modified range, we can use binary search. But, we can be clever here too, as the binary search will be an overkill. Since the range we want is always a prefix of the array we can just check the first element of the vector and decide whether any string lies in the required range or not. To get a clear picture of the above, you can see the below picture of the trie build from the sample case in the problem. It also contains how the answer to different queries are arrived at. Once, you are clear with the above idea, you can see the editorialist implementation below for help. Feel free to share your approach, if it was somewhat different. Time Complexity$O(Q\log{Q} + \text{Sum of length of strings} * \text{ALPHABET})$ for offline solution $O(\text{Sum of length of strings} * \text{ALPHABET})$ for online solution where $\text{ALPHABET} = $ number of distinct english character (26 for this problem). Space Complexity$O(\text{Sum of length of strings})$ AUTHOR'S AND TESTER'S SOLUTIONS:Author's solution can be found here. Editorialist's solution can be found here.
This question is marked "community wiki".
asked 06 Jun, 18:58

In case if you don't want to use data structure,Sort N+q strings with keep track of indices of q strings and then for every query check strings above and below it in the sorted list upto a condition and find the lexicographically smallest with longest LCP. It works fine. answered 11 Jun, 18:15

I used a hashtable to hash all the substrings and keep track of all the indices of the strings having the substring. Sort all the substrings lexicographically. Then when the queries come, iterate through the substrings of P from largest to smallest. For each substring, break once you get an index <= r. Solution here. answered 11 Jun, 18:30

I used an entirely different approach, working in C#. As each string is no more than 10 characters, each one of 26 lower case letters, each entire string can be encoded into a 'long', with 5 bits per letter. Comparisons like 'CompareTo' are then fast. Define a class StringIndex, consisting of an encoded string and its index in the array. Build a sorted list of StringIndex, sorted by the integer encoded string. For each query, find its place in the sorted list by a binary search. From there search forwards until an index within range, and set the common prefix with that string. Then search backwards. Check whether the first one with an index in range has a longer common prefix. Search backwards until there is a shorter common prefix. When no common prefix is found, set to the first string in the list with an index in range. As the number being searched may be much less than the number of strings supplied, extract a series of shorter lists before starting any queries, and then choose the appropriate list to search for each query. My submission may be found at https://www.codechef.com/viewsolution/18780484 It earned 100 points in 0.43 seconds. answered 17 Jun, 06:15

Just a small memory optimization: We only need to store a vector for the nodes at which strings end. For other nodes, we could just store the index of the first string from the left which passes through that node, since we are anyway going to take the min. Nice problem! And good editorial! :) answered 11 Jun, 16:17

Please add the links to the actual coded solutions of editorialist/author/tester. Right now, they just redirect to this page itself. answered 11 Jun, 17:28

I implemented a trie for this problem but only for task #3 it is giving WA and for rest 5 test cases it is giving AC can anybody help me out with what is wrong in my code https://www.codechef.com/viewsolution/18767595 answered 11 Jun, 17:58
use insert code option and then place your code
(11 Jun, 18:04)
Please give link to your submission. Pasting code is tedious and takes lot of visible space.
(11 Jun, 18:14)

can anyone explain me traverse_down function of testers code please.....thanks in advance answered 11 Jun, 23:13

I used similar approach as the second one. Just instead of storing vector of indices I stored lowest index of string which the character is part of. Unfortunately My code is erring out in task 3. Can any body point the bug ? Here's the link. Also nice editorial. Thanks. Just few small corrections though  1) The tester has actually used approach 2 in his/her code. 2) The editorials' code cannot be opened  Access denied in XML tree. answered 11 Jun, 23:30
There was an issue while linking the code. It is updated now.
(12 Jun, 08:23)
Okay. The editorialists' code was being displayed while clicking on testers' solution. Thanks. Btw Any comments regarding my code ?
(12 Jun, 11:30)
