You are given a string pattern of lower-case letters and a string s of words separated by single spaces. Decide whether s follows the pattern.
It follows the pattern when the letters and words pair up one to one: there is one word per letter, read left to right, every copy of a letter stands for the same word, and two different letters never stand for the same word. Return true or false.
Example 1
Input: pattern = "abab", s = "sun moon sun moon" Output: true Why: a is always sun, b is always moon
2 more examples and the constraints
Example 2
Input: pattern = "abab", s = "sun sun sun sun" Output: false Why: a and b would both stand for sun
Example 3
Input: pattern = "aab", s = "up up" Output: false Why: three letters but only two words
Constraints
- 1 ≤ length of pattern ≤ 300, lower-case letters only
- 1 ≤ length of s ≤ 3,000
- s has lower-case words, one space between each, and no space at either end
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Check every pairO(n² · w)
- Two hash mapsO(n + L)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 300 words | Verdict |
|---|---|---|---|
| Check every pair | O(n² · w) | Mention it, then move on | |
| Two hash maps | O(n + L) | Best; one pass |
n = number of letters, w = longest word, L = length of s.
Edge cases to test
- Counts differ. "aab" with "up up", or "a" with "go go": false before any map is used.
- Two letters, one word. "abab" with "sun sun sun sun" passes the letter map but fails the word map.
- One letter, two words. "aa" with "red blue" fails the letter map.
- Similar words. "car" and "cart" are different words; compare whole words, not prefixes.
Common mistakes
- Using only the letter-to-word map, so two letters can share one word.
- Forgetting to compare the counts first, which reads past the end or ignores extra words.
- Comparing Java strings with == instead of equals.
How to talk through it
- 1Clarify. One space between words? Can two letters mean the same word? (No, it must be one to one.)
- 2Give the pair check. Same letter must mean same word, for every pair. Say it is O(n²).
- 3Name the bijection. One to one needs a check in each direction, so keep two maps.
- 4Code the one pass. Compare counts, then check both maps before storing each pair.
- 5Test out loud. Run a count mismatch and "abab" with four equal words before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?