Hi there, I am starting the year, publishing optimized solutions to leetcode DSA questions, ranging from Easy, Medium to Hard.
Now to the Day 1 Question on Word patterns
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
Contraints given :
1 <= pattern.length <= 300
pattern
contains only lowercase English letters.1 <= s.length <= 3000
s
contains only lowercase English letters and spaces' '
.s
does not contain any leading or trailing spaces.All the words
s
are separated by a single space.Now let's get started with the solution
There's actually a pattern of a string s, to follow, and the logic revolves around if the string follows that particular pattern, The examples above clearly show the pattern which evaluates to a truism and also otherwise.
The pattern itself can be compared to an array of items in this case we are referring to an array of strings(words) that coincides with the pattern initially given
JavaScript method like split and the strict equality operator is prioritized here, to give the correct solution
Split method: this method splits a string into an array of substrings, looking at the examples, that's what is playing out looking at it logically. For further reading on the JavaScript Split method, click here
Strict equality operator (===): This operator compares two operands, It strictly checks if two operands are the same returning a boolean value. Here the pattern and the array of words are compared.
The code is given below
/**
* @param {string} pattern
* @param {string} s
* @return {boolean}
*/
var wordPattern = function(pattern, s) {
// split function being used here
const arr = s.split(" ");
if (pattern.length !== arr.length) {
return false;
}
// looping through the array
for (let i = 0; i < pattern.length; i++) {
for (let j = i + 1; j < pattern.length; j++) {
// comparing the pattern and strings,s of array
if (!(pattern[i] === pattern[j]) === (arr[i] === arr[j])) {
return false;
}
}
}
return true;
}
The code above shows the concise solution to the word pattern problem with the Time complexity of the function being 0(n).
Thanks for reading, Your views are highly welcomed. Stick with me till Day 2