Update appNew update is available. Click here to update.
Last Updated: 24 Dec, 2020
Word Pattern
Easy
Problem statement

You have been given two strings 'S' and β€˜T’. Your task is to find if β€˜S’ follows the same pattern as β€˜T’.

Here follow means a full match, i.e. there is a bijection between a letter of β€˜T’ and a non-empty word of β€˜S’.

For Example:
If the given string is S = "lion cow cow lion" and T = β€œwccw”, then the string β€˜S’ follows the same pattern as string β€˜T’.
Note:
'T’ contains only lowercase English letters.

β€˜S’ contains only lowercase English letters and spaces.

β€˜S’ does not contain any trailing or leading spaces. All words in β€˜S’ are separated by a single space.
Input Format:
The first line contains an integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.

The first line of each test case contains a string β€˜S’.

The second line of each test case contains a string β€˜T’.
Output Format:
For each test case, the only line of output will print β€œYes” if β€˜S’ follows the same pattern as β€˜T’. Else print β€œNo”.

Print the output of each test case in a separate line.
Note:
You are not required to print the expected output, it has already been taken care of. Just implement the function.
Constraints:
1 <= t <= 100
1 <= |S| <= 5000
1 <= |T| <= 5000

Time Limit: 1 second
Approaches

01Approach

We will use two hashmaps β€˜charToWord’ and β€˜wordToChar’ to track which character of β€˜T’ maps to which word of β€˜S’ and which word of β€˜S’ maps to which character of β€˜T’,  respectively.

 

Here is the algorithm:

  1. We initialise two hashmaps β€˜charToWord’ and β€˜wordToChar’.
  2. We scan each character-word pair
    1. If the character is not present in β€˜charToWord’ 
      1. If the word is already present in β€˜wordToChar’ 
        1. Return β€œNo”. Since it has been mapped with some other character before.
      2. Else
        1. Map the character of β€˜T’ to the word of β€˜S’.
        2. Map the word of β€˜S’ to the character of β€˜T’.
    2. Else
      1. If the current word is not equal to the word that character maps to in β€˜charToWord’ 
        1. Return β€œNo”.
  3. Finally, return β€œYes”.