Ctrl K

Words Shaped Like a Template

Medium
You are given a list of words words and a template word template. A word fits the template if the template's letters can be swapped for other letters one-to-one so that the template turns into that word: equal letters of the template become equal letters, and different letters become different ones. For example, "add" fits the template "egg", but "aaa" does not (the distinct e and g would become the same letter), and neither does "abc". Return every word from words that fits the template, in any order.
Example 1
words=["noon", "deed", "tree", "abba", "moon"], template="otto" → ['noon', 'deed', 'abba']

In "otto" the first and last letters are equal, and the two middle ones are equal to each other but different. "noon", "deed" and "abba" share this shape; "tree" and "moon" repeat letters in other places.

Example 2
words=["aaa", "abc", "xyx"], template="cat" → ['abc']

All letters of "cat" differ, so only "abc" fits: "aaa" and "xyx" repeat letters.

Example 3
words=["q", "z"], template="m" → ['q', 'z']
Constraints
  • 1 ≤ len(template) ≤ 20
  • 1 ≤ len(words) ≤ 50
  • len(words[i]) = len(template)
  • All strings consist of lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsAnagram Buckets MediumSplit Into Dictionary Words MediumWords Equal Up to a Shift MediumA Subsequence of One Word Only MediumFiles With the Same Content Medium
loading Python…
Input
words=["noon", "deed", "tree", "abba", "moon"], template="otto"
Expected
['noon', 'deed', 'abba']

Run checks the first 3 tests in your browser. Submit checks all 108 tests on the server, hidden ones included.