1. Split and Word Set Validation
Intuition
Split s by space. If word count != pattern.length, return false. Map c to word. If c already seen, verify charToWord[c] == word. Else, verify word is not already in usedWords set; add to map and set.
When to apply: Basic baseline comparison.
Algorithm
- Split
sintowords. - If
pattern.length != words.length: return false. - Initialize
charToWord = {},usedWords = Set(). - For
ifrom 0 topattern.length - 1: -
c = pattern[i], w = words[i]. - If
cincharToWord: - If
charToWord[c] != w: return false. - Else:
- If
usedWords.has(w): return false. -
charToWord[c] = w; usedWords.add(w). - Return true.
Split and Word Set Validation Trace
2 of 2 questions left todayObservation: Split s by spaces into array ["dog", "cat", "cat", "dog"]
Observation: Split s by spaces into array ["dog", "cat", "cat", "dog"].
Decision: pattern.length === words.length === 4. Continue validation.
Invariant: Equal token count.
#include <iostream>#include <string>#include <vector>#include <sstream>#include <unordered_map>#include <unordered_set> class Solution {public: bool wordPattern(std::string pattern, std::string s) { std::vector<std::string> words; std::stringstream ss(s); std::string word; while (ss >> word) words.push_back(word); if (pattern.size() != words.size()) return false; std::unordered_map<char, std::string> c2w; std::unordered_set<std::string> usedWords; for (size_t i = 0; i < pattern.size(); ++i) { char c = pattern[i]; const std::string& w = words[i]; if (c2w.count(c)) { if (c2w[c] != w) return false; } else { if (usedWords.count(w)) return false; c2w[c] = w; usedWords.insert(w); } } return true; }}; int main() { Solution sol; std::cout << (sol.wordPattern("abba", "dog cat cat dog") ? "true" : "false") << std::endl; // true std::cout << (sol.wordPattern("abba", "dog cat cat fish") ? "true" : "false") << std::endl; // false return 0;}Time & Space Complexity
- Time complexity:
O(N + M)— Splits string and processes N tokens in linear time. - Space complexity:
O(N + M)
Why Brute Force Doesn't Scale:
Single pass index recording eliminates double map lookups.
Lightweight integer index maps.