FOR FREE CONTENT

Word mismatch replica

Back to Programming

Description

You are given the words in the magazine and the words in the note. Print ‘Yes’ if you can replicate the note exactly using whole words from the magazine otherwise print ‘No’. The words in the note are case sensitive. You can only use whole worse available in the magazine.

For example, the note is “Attack at dawn”. The magazine contains only “attack at dawn”. The magazine has all the right words, but there’s a case Mismatch. The answer is 'No' 

Algorithm

Magazine: “attack at down”

Note: “Attack at down”     //The words present in note is same as magazine but ‘A’ in ‘Attack’ is different from ‘a’ in ‘attack’ so, answer is no.

 

Example:

Magazine: Give me one grand today night

Note: ‘give one grand today’

The words present in note is same as Magazine and all are in lowercase.

O/P: Yes

 

Step 1: Initialize a variable c with ‘Yes’

Step 2: Using the concept of dictionary. Store the frequency of each word in Magazine to dictionary.

Step 3: for each word in note, check whether present in dictionary.

                        if not present or the value of the word in dictionary < = 0

                                    store ‘No’ in c and break

                       else

                                   decrement the value in dictionary by 1

Step 4: Repeat Step 3 until condition of loop is false

Step 5: Check whether the value in c is ‘Yes’ or ‘No’

             if ‘Yes’ then print “Yes”

            else print “No”

Basically, we are first counting the occurrence of each word in Magazine and storing it in the dictionary then again we are taking the word in a note and checking whether exists in the dictionary. If found then decrement the value by 1 else we found that the word is not taken from Magazine, directly print ‘No’.

Also, check that if the value for corresponding word is < = 0, it means that number of times the word used in note is greater than number of times word present in Magazine. Hence print No.

Code

Time Complexity: O(Max(length of Magazine, length of note))    //Using a dictionary on an average case it takes O(1) to find.

Space Complexity: O(length of the magazine)  //for storing the frequency of words