↓Skip to main content
  1. LeetCode/

LeetCode 290: Word Pattern

·1 min· ·
LeetCode Easy Hash-Table String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-23

  • Submissions: Accepted (first try)

Approach
#

A bijection as in LC 205: each character maps to one word and each word to one character. The lengths must match, and the numbers of distinct characters, distinct words and distinct (character, word) pairs must all be equal (Hash Table Template 5).

My Attempts
#

Passed on the first try, by recording the position list of every character and every word and comparing the two collections of position lists.

Solution
#

class Solution:
    def wordPattern(self, pattern: str, s: str) -> bool:
        words = s.split()
        if len(pattern) != len(words):
            return False
        return len(set(pattern)) == len(set(words)) == len(set(zip(pattern, words)))

Complexity
#

Time O(n + m), space O(n + m).

Mistakes to Avoid
#

  • Rule out different lengths first; zip silently truncates.
  • Both directions must be one to one: "ab" with "dog dog" fails.

Interview Explanation
#

This is a bijection: after checking the lengths match, I compare the counts of distinct characters, distinct words and distinct pairs. Time O(n + m).

Related

LeetCode 383: Ransom Note
·1 min
LeetCode Easy Hash-Table String Counting
LeetCode 383 note: every character’s demand in ransomNote must not exceed its supply in magazine; an empty Counter difference means yes
LeetCode 387: First Unique Character in a String
·1 min
LeetCode Easy Hash-Table String Queue Counting
LeetCode 387 note: count first, then scan left to right for the first character with count 1
LeetCode 389: Find the Difference
·1 min
LeetCode Easy Hash-Table String Bit-Manipulation Sorting
LeetCode 389 note: t has one extra character; XOR every character of both strings, pairs cancel, and the extra one remains
LeetCode 409: Longest Palindrome
·2 mins
LeetCode Easy Hash-Table String Greedy
LeetCode 409 note: use an even number of each character on the two sides, plus one in the middle if any count is odd
LeetCode 242: Valid Anagram
·2 mins
LeetCode Easy Hash-Table String Sorting
LeetCode 242 note: two strings are anagrams exactly when their character counts match; compare Counters or sorted strings
LeetCode 205: Isomorphic Strings
·2 mins
LeetCode Easy Hash-Table String
LeetCode 205 note: characters must map one to one; it holds when the distinct characters and distinct pairs all have the same count