Word Amalgamation

Interview

Time limit1sMemory limit128 MB

Summary
For each scrambled word, print all dictionary words that are anagrams of it in alphabetical order, or NOT A VALID WORD.
Level

Easy3 of 10

Topics
Hash map, Sorting, String, Brute force
Solved
No attempts yet

Problem

Across millions of newspapers in the United States there is a word game called Jumble. The goal of the game is to solve a riddle, but to find the letters that make up the answer you must first unscramble a set of words. Your task is to write a program that unscrambles words.

Input

The input consists of four parts:

  1. A dictionary of at least 1 and at most 100 words, one word per line.
  2. A line containing only XXXXXX, which marks the end of the dictionary.
  3. One or more scrambled "words" that you must unscramble, each on its own line.
  4. Another line containing only XXXXXX, which marks the end of the input.

Every word, both the dictionary words and the scrambled words, consists only of lowercase English letters and is between 1 and 6 characters long. (Note that the sentinel XXXXXX uses uppercase X's.) The dictionary is not necessarily sorted, but each word in it is unique.

Output

For each scrambled word in the input, output, in alphabetical order, every dictionary word that can be formed by rearranging its letters. Print each such word on its own line. If no dictionary word can be formed (the list is empty), print the single line NOT A VALID WORD instead. In both cases, print a line of six asterisks (******) to mark the end of the list.

Examples2

  1. Example 1

    Input
    tarp
    given
    score
    refund
    only
    trap
    work
    earn
    course
    pepper
    part
    XXXXXX
    resco
    nfudre
    aptr
    sett
    oresuc
    XXXXXX
    
    Expected output
    score
    ******
    refund
    ******
    part
    tarp
    trap
    ******
    NOT A VALID WORD
    ******
    course
    ******
    
  2. Example 2

    Input
    cat
    XXXXXX
    act
    dog
    XXXXXX
    
    Expected output
    cat
    ******
    NOT A VALID WORD
    ******