Words Magic with Prefix Replacement Problem

Ninja is provided with a dictionary of words, WORDS, and a sentence, SENTENCE, which consists of words separated by spaces. The goal is to minimize the size of the SENTENCE by replacing its words using the following rule:

Ninja can replace a word from the SENTENCE with a word from WORDS if and only if a prefix of that word exists in WORDS. If multiple replacements are possible, choose the smallest word among them.

Example of Prefixes:

For the string ‘abcd’, the prefixes are: "a", "ab", "abc", "abcd".
Input:
The first line contains an integer ‘T’, the number of test cases.
Each test case consists of:
- First line with integer ‘N’, the number of words in WORDS.
- Second line with ‘N’ space-separated words.
- Third line with a string, the SENTENCE.
Output:
For each test case, output the minimized SENTENCE based on the replacement rule on a new line.

Constraints:

  • 1 <= T <= 100
  • 1 <= N <= 100
  • Each word in WORDS consists of lowercase letters only.
  • 1 <= |SENTENCE| <= 100000
  • The SENTENCE has no leading or trailing spaces.

Note:

You do not need to print the output explicitly; the function itself handles outputting results.

AnswerBot
4mo

The goal is to minimize the size of a sentence by replacing words with prefixes from a given dictionary.

  • Iterate through each word in the sentence and check if a prefix exists in the dictionary

  • Replace ...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Interview Questions Asked at Barclays

Q. What is the difference between static and final?
Q. What is data encapsulation?
Q. Is multiple inheritance allowed in Java?
Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

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

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits