Given a pattern and a string s, find if s follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.

Input: pattern = "abba", s = "dog cat cat dog"
Output: true
Explanation: here 'a' can be mapped to 'dog' and 'b' can be mapped to 'cat' and vice versa.
Input: pattern = "abba", s = "dog cat cat fish"
Output: false
Explanation: 'a' has two different mappins, so it is not following the pattern.
Input: pattern = "abba", s = "cat cat cat cat"
Output: false
Explanation: here both 'a' and 'b' mapped to same words, so it is not following the pattern.

Contents

In this approach, we are going to store mapping of letters of pattern to words in s into a HashMap and from word to letter into another HashMap. The reason why we do this is because we need to check no two letters mapped to same word (as shown is example 3 above) to.

Implementation details
import java.util.HashMap; public class WordPattern { static boolean usingHashMapToStoreMapping(String pattern, String s) { String[] words = s.split(" "); if(pattern.length() != words.length) { return false; } HashMap<Character, String> map_c_word = new HashMap<>(); HashMap<String, Character> map_word_c = new HashMap<>(); for(int i=0; i<pattern.length(); i++) { char c = pattern.charAt(i); String wordValAfter = map_c_word.putIfAbsent(c, words[i]); if(wordValAfter != null && !wordValAfter.equals(words[i])) { return false; } Character cValAfter = map_word_c.putIfAbsent(words[i], c); if(cValAfter != null && !cValAfter.equals(c)){ return false; } } return true; } }
Complexity Analysis:

Time complexity: Above code runs in O(n) time where n is the input string pattern length.
Space complexity: O(m* n) since we are storing all words from string s and m is the average length of a word.

Above implementations source code can be found at GitHub link for Java code