LeetCode September Challenge(Day-7)

Asish Raz
2 min readSep 15, 2020
leetcode

Topic — Word Pattern

Q. 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

Example 1:

Input: pattern = "abba", s = "dog cat cat dog"
Output: true

Example 2:

Input: pattern = "abba", s = "dog cat cat fish"
Output: false

Example 3:

Input: pattern = "aaaa", s = "dog cat cat dog"
Output: false

Example 4:

Input: pattern = "abba", s = "dog dog dog dog"
Output: false

Constraints:

  • 1 <= pattern.length <= 300
  • pattern contains only lower-case English letters.
  • 1 <= s.length <= 3000
  • s contains only lower-case English letters and spaces ' '.
  • s does not contain any leading or trailing spaces.
  • All the words in s are separated by a single space.

Logic:

  • Firstly, find the length of the pattern and the given string(It should be same)
  • Split the given string into list separated by the empty space
  • Then, put them into the set data type, to get the distinct element of the pattern and as well as the given string. Capture the length of both and this should too be the same length
  • With the use of zip method, zip both the pattern and the given string so that, we can observe the full match is there or not.
  • Now, capture the distinct element from the above zip method in the pattern and the given string by using set data type
  • And finally find the length of the above value and that’s it.

If the length of the pattern and the length of the given string are same and length of the unique elements in pattern equals with length of the unique elements in the given string are also same, then we can return True, otherwise False.

Code:

code

Happy Coding!!!

Here is the leetcode link:
https://leetcode.com/explore/featured/card/september-leetcoding-challenge/554/week-1-september-1st-september-7th/3451/

Please feel free to comment, if you have any problem or doubt.

Thank You!!!
Never settle and always Hustle!!!

-Gareeb CODER

(Thanks for your time and do encourage me to write more by clapping.)

--

--

Asish Raz

entrepreneur, moody, moody writer, moody singer, traveller, hangout lover