Ninja and words magic

Ninja has been given a dictionary of words ‘WORDS’ of length ‘N’ and a sentence ‘SENTENCE’ consisting of words separated by a single space. Ninja has to make the ‘SENTENCE’ as small as possible by performing the below operation any number of times.

Ninja can replace a word of the ‘SENTENCE’ with a word present in the ‘WORDS’ if and only if the prefix of that word is present in the ‘WORDS’.

Note: If the word of the ‘SENTENCE’ can be replaced by more than one word present in the ‘WORDS’, then replace it with the smallest possible word present in the ‘WORDS’.

Example for all prefixes of a string:

String ‘STR’ = “abcd” 
Then all possible prefix of this ‘STR’ are:
"a", "ab", "abc", "abcd".

Note:

1. All the words in the ‘WORDS’ and the ‘SENTENCE’ contain only lower case English alphabets.
2. ‘SENTENCE’ does not have any leading and trailing spaces.

Can you help Ninja to make the ‘SENTENCE’ as small as possible by performing the given operation?.

Input Format
The first line of input contains an integer ‘T’ which denotes the number of test cases or queries to be run.

The first line of each test case will contain an integer ‘N’ representing the number of words in the ‘WORDS’.

The second line of each test case will contain ‘N’ single space-separated strings representing the words in the ‘WORDS’.

The third line of each test case will contain a string that represents the ‘SENTENCE’. 
Output Format :
For each test case, print a single line containing string denoting the ‘SENTENCE’ after making it as small as possible by performing the given operation.

The output of each test case will be printed in a separate line.

Note:

You do not need to print anything; it has already been taken care of. Just implement the given function.
Constraints:
1 <= ‘T’ <= 100
1 <= ‘N’ <= 100
‘WORDS[ i ]’ = {a to z}
1 <= | ‘SENTENCE’ | <= 100000

Where ‘T’ denotes the total number of test cases, ‘N’ represents the number of words in the ‘WORDS’, and | ‘SENTENCE’ | denotes the length of the ‘SENTENCE’.

Time Limit: 1 second
CodingNinjas
author
2y
Hashing

First, we will store all the words of ‘WORDS’ in a HashSet ‘WORDS_SET’ and then traverse all the words of the ‘SENTENCE’ and look for the prefix of each word present in the ‘WORDS_SET’ or not. ...read more

Help your peers!
Add answer anonymously...
Barclays Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter