Word Pattern

Check whether a pattern's characters bijectively match words in a sentence.

Easy
Time O(N) Space O(N)
LeetCode
4 min read
hash-map strings

Problem#

Given a pattern of characters and a space-separated string s, return true iff there is a bijection between pattern chars and words such that pattern[i] maps to the i-th word.

Examples#

  • pattern = "abba", s = "dog cat cat dog"true.
  • pattern = "abba", s = "dog cat cat fish"false.
  • pattern = "aaaa", s = "dog cat cat dog"false.

Constraints#

  • 1 <= pattern.length <= 300. s is non-empty lowercase words separated by single spaces.

Hints#

Hint
Bijection means two maps: char->word and word->char.

Approach#

Split s into words; require the count to match pattern.size(). Two maps enforce both directions of the bijection; conflict on either side returns false.

Solution#

Word Pattern
class Solution {
public:
bool wordPattern(string pattern, string s) {
vector<string> words;
string cur;
s.push_back(' ');
for (char c : s) {
if (c == ' ') { if (!cur.empty()) { words.push_back(std::move(cur)); cur.clear(); } }
else cur.push_back(c);
}
if (words.size() != pattern.size()) return false;
unordered_map<char,string> c2w;
unordered_map<string,char> w2c;
for (int i = 0; i < (int)pattern.size(); ++i) {
char p = pattern[i];
const string& w = words[i];
auto itC = c2w.find(p);
auto itW = w2c.find(w);
if (itC == c2w.end() && itW == w2c.end()) { c2w[p] = w; w2c[w] = p; }
else if (itC == c2w.end() || itW == w2c.end()) return false;
else if (itC->second != w || itW->second != p) return false;
}
return true;
}
};

Editorial#

Same shape as Isomorphic Strings — only the “alphabet” on one side is words instead of single characters. Either-side absence with the other present is a contradiction (the mapping would be many-to-one), hence the explicit handling. Tokenize first to avoid index gymnastics.

Complexity#

  • Time: O(N).
  • Space: O(N).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.