Given a pattern string of lowercase letters and a space-separated string of words, determine if the string follows the same pattern. A full match means there is a bijection (one-to-one mapping) between each pattern letter and each word. Return false if either input is null or if the number of pattern characters does not equal the number of words.
Examples:
Input: pattern = 'abba', str = 'dog cat cat dog'
Output: true
Explanation: a maps to dog and b maps to cat consistently in both directions
Input: pattern = 'abba', str = 'dog cat cat fish'
Output: false
Explanation: a maps to dog initially but the last word is fish, breaking the pattern
Input: pattern = 'abba', str = 'dog dog dog dog'
Output: false
Explanation: a and b both map to dog, violating the bijection requirement
Input: pattern = null, str = 'dog cat'
Output: false
Explanation: Null pattern input returns false
Input: pattern = 'abc', str = 'dog cat'
Output: false
Explanation: Pattern has 3 characters but the string has only 2 words
Apex Code Editor
Welcome to Lightning Challenge!
Create an Account
Sign up to track your progress, earn points, and compete with others. Your solutions will be saved automatically.
Create accountHow It Works
- • Write your solution in the code editor
- • Connect your Salesforce org to test
- • Submit to check if your solution passes
- • Use hints if you get stuck
Contest Alert
🏆 #CodeEveryDay Mar/April 2026
Contest runs March 3 - April 30. Complete challenges to climb the leaderboard!
Points are calculated for challenges completed during the contest period.