Skip to the code
+25 XP

#37 Words With the Same Letter Pattern

medium

A puzzle app groups words that have the same letter pattern: "foo", "bee", and "add" all follow the pattern "one letter, then a different letter twice". Formally, two words share a pattern if they have the same length and, at every pair of positions, their letters are either equal in both words or different in both words.

Write samePatternGroups(words) that returns the groups of words sharing a pattern, keeping only groups with at least two words. Order groups by their first word's position in words, and keep words inside a group in their original order.

Example 1

Input: words = ["foo","bar","bee","add","egg","cat"]
Output: [["foo","bee","add","egg"],["bar","cat"]]

foo, bee, add, and egg repeat their last letter; bar and cat have three different letters.

Example 2

Input: words = ["abc","aaa"]
Output: []

The two words have different patterns, so no group has two words.

Constraints

  • 0 <= words.length <= 10^5
  • 1 <= words[i].length <= 50
  • All the words together have at most 10^6 letters.
  • Words use lowercase letters.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).