Skip to content

Files

Latest commit

 

History

History
59 lines (44 loc) · 1.63 KB

0290. Word Pattern.md

File metadata and controls

59 lines (44 loc) · 1.63 KB

Screen Shot 2023-01-20 at 3 13 55 PM

The time complexity of this function is O(n), where n is the length of the input pattern. The for loop iterates through each character in the pattern once, and the map.has and map.set operations have an average time complexity of O(1). Therefore, the overall time complexity is linear with respect to the size of the input.

The space complexity of this function is O(n), where n is the length of the input pattern. The function creates a new map and uses an array to store the words of the input string. In the worst case, all the characters in the pattern will be distinct, so the map will contain n key-value pairs, and the array will contain n elements. Therefore, the overall space complexity is linear with respect to the size of the input.

/**
 * @param {string} pattern
 * @param {string} s
 * @return {boolean}
 */
var wordPattern = function(pattern, s) {
    let map = new Map();
    s = s.split(" ");
    if(pattern.split("").length !== s.length) return false;

    for(let i = 0; i < pattern.length; i++) {
        if(map.has(pattern[i])) {
            if(map.get(pattern[i]) !== s[i]) {
                return false;
            }
        } else {
            map.set(pattern[i], s[i]);
        }
    }
    return new Set([...map.values()]).size === map.size;
};

/*
a b b a
dog dog dog dog 

a -> dog 
b -> dog
b -> dog
a -> dog

new Set([...map.values()]).size === 1
map.size === 2
return false

a b b a
dog cat cat dog 

a -> dog 
b -> cat
b -> cat
a -> dog


*/