GeeksforGeeks App
Open App
Browser
Continue

# Check if words in given sentence occur based on the given pattern

Given a pattern ‘pattern‘ and a sentence ‘s‘, the task is to check if the words in the given sentence occur based on the pattern represented in the ‘pattern‘.
Examples:

Input: pattern = “abba”, s = “geeks for for geeks”
Output: true
Explanation: In the pattern, ‘a’ denotes ‘geeks’ and ‘b’ denotes ‘for’. Therefore, sentence ‘s’ follows the pattern ‘pattern’

Input: pattern = “abc”, s = “geeks for geeks”
Output: false

Approach: The given problem can be solved by generalizing the pattern formed by words in a given sentence and the characters in the given pattern. Then just check if both the generalized pattern and the given pattern are the same or not. Follow the below steps to solve the problem:

• Create a map to store each word and assign a value to each unique word based on its occurrence.
• Example: for sentence “geeks for for geeks”, the map will be [{“geeks”, 0}, {“for”, 1}]
• Similarly, map the occurrence of each character in the pattern
• Then match the pattern index by index in both maps and print the result

Below is the implementation of the above approach:

## C++

 // C++ program for the above approach#include using namespace std; // Function to check if the words in given// sentence follows the given patternbool wordPattern(string pattern, string s){    // Stores the occurrence of each word    // of a sentence    map mp;    int ch = -1;    string temp = "";    string str = "", p = "";    for (int i = 0; i < s.length(); i++) {        if (s[i] == ' ') {             if (!temp.empty()                && mp.find(temp) == mp.end()) {                 mp.insert({ temp, ++ch });            }            if (mp.find(temp) != mp.end())                str += ((char)((mp.find(temp))->second                               + 'a'));            temp = "";        }        else            temp += s[i];    }    if (!temp.empty()        && mp.find(temp) == mp.end())        mp.insert({ temp, ++ch });     if (mp.find(temp) != mp.end())        str += ((char)((mp.find(temp))->second + 'a'));     map m;    ch = -1;    for (int i = 0; i < pattern.length(); i++) {        if (m.find(pattern[i]) == m.end())            m.insert({ pattern[i], ++ch });        if (m.find(pattern[i]) != m.end())            p += ((char)((m.find(pattern[i]))->second                         + 'a'));    }     return p == str;} // Driver Codeint main(){     string pattern = "abba",           s = "geeks for for geeks";    cout << (wordPattern(pattern, s)                 ? "true"                 : "false");    return 0;}

## Java

 // Java program for the above approachimport java.util.*; class GFG{ // Function to check if the words in given// sentence follows the given patternstatic boolean wordPattern(String pattern, String s){    // Stores the occurrence of each word    // of a sentence    HashMap mp = new HashMap<>();    int ch = -1;    String temp = "";    String str = "", p = "";    for (int i = 0; i < s.length(); i++) {        if (s.charAt(i) == ' ') {             if (!temp.isEmpty()                && mp.containsKey(temp)) {                 mp.put( temp, ++ch );            }            if (mp.containsKey(temp))                str += mp.get(temp)                               + 'a';            temp = "";        }        else            temp += s.charAt(i);    }    if (!temp.isEmpty()        && mp.containsKey(temp) )        mp.put( temp, ++ch );     if (mp.containsKey(temp))        str += mp.get(temp) + 'a';     HashMap m = new HashMap<>();    ch = -1;    for (int i = 0; i < pattern.length(); i++) {        if (m.containsKey(pattern.charAt(i)))            m.put( pattern.charAt(i), ++ch );        if (m.containsKey(pattern.charAt(i)))            p +=m.get(pattern.charAt(i)) + 'a';    }     return p == str;} // Driver Codepublic static void main(String[] args){     String pattern = "abba",           s = "geeks for for geeks";    System.out.print((wordPattern(pattern, s)                 ? "true"                 : "false"));}} // This code is contributed by Rajput-Ji

## Python3

 # Python program for the above approach# Function to check if the words in given# sentence follows the given patterndef wordPattern(pattern, s):     # Stores the occurrence of each word    # of a sentence    mp = {}    ch = -1    temp = ""    st = ""    p = ""     for i in range(0, len(s)):        if (s[i] == ' '):            if ((len(temp)) and (not mp.__contains__(temp))):                ch += 1                mp[temp] = ch            if (mp.__contains__(temp)):                st += ((chr)((mp[temp])                             + 97))            temp = ""        else:            temp += s[i]     if ((len(temp)) and (not mp.__contains__(temp))):        ch += 1        mp[temp] = ch     if (mp.__contains__(temp)):        st += ((chr)((mp[temp]) + 97))     m = {}    ch = -1     for i in range(0, len(pattern)):        if (not m.__contains__(pattern[i])):            ch += 1            m[pattern[i]] = ch         if (m.__contains__(pattern[i])):            p += ((chr)(m[pattern[i]] + 97))     return p == st # Driver Codepattern = "abba"s = "geeks for for geeks"ans = wordPattern(pattern, s)print("true" if ans else "false") # This code is contributed by ninja_hattori.

## C#

 // C# program for the above approachusing System;using System.Collections.Generic;public class GFG {   // Function to check if the words in given  // sentence follows the given pattern  static bool wordPattern(String pattern, String s)  {     // Stores the occurrence of each word    // of a sentence    Dictionary mp = new Dictionary();    int ch = -1;    String temp = "";    String str = "", p = "";    for (int i = 0; i < s.Length; i++) {      if (s[i] == ' ') {         if (temp.Length != 0 && mp.ContainsKey(temp)) {           mp.Add(temp, ++ch);        }        if (mp.ContainsKey(temp))          str += mp[temp] + 'a';        temp = "";      } else        temp += s[i];    }    if (temp.Length != 0 && mp.ContainsKey(temp))      mp.Add(temp, ++ch);     if (mp.ContainsKey(temp))      str += mp[temp] + 'a';     Dictionary m = new Dictionary();    ch = -1;    for (int i = 0; i < pattern.Length; i++) {      if (m.ContainsKey(pattern[i]))        m.Add(pattern[i], ++ch);      if (m.ContainsKey(pattern[i]))        p += m[pattern[i]] + 'a';    }     return p == str;  }   // Driver Code  public static void Main(String[] args) {     String pattern = "abba", s = "geeks for for geeks";    Console.Write((wordPattern(pattern, s) ? "true" : "false"));  }} // This code is contributed by Rajput-Ji

## Javascript



Output

true

Time Complexity: O(NlogN), as we are inserting elements into map and finding values from the map inside the loop.
Auxiliary Space: O(N), as we are using extra space for map.

My Personal Notes arrow_drop_up