FastPrepCount Phrases Formed by Anagram Replacement

Count Phrases Formed by Anagram Replacement

Wells Fargo logoWells Fargo● EasyINTERNOA

Problem statement

Two words are anagrams when one can be made by rearranging all the letters of the other. A word counts as an anagram of itself.

You are given an array words of different lowercase words and an array phrases. Each phrase is a small sentence made from words in words, separated by single spaces.

To make a new phrase, replace each word of a phrase with any of its anagrams from words. Each position chooses on its own, even when the same word appears more than once. The original phrase is one of the results.

Return an array answer where answer[i] is the number of phrases that can be made from phrases[i].

Function

countPhrases(words: String[], phrases: String[]) → long[]

Examples

Example 1

words = ["stop","pots","tops","on","no","go"]phrases = ["stop on go","go no"]return = [6,2]

stop has 3 anagrams in words: stop, pots, and tops. on has 2: on and no. go has only itself.

  • "stop on go" can be made in 3 * 2 * 1 = 6 ways.
  • "go no" can be made in 1 * 2 = 2 ways: "go no" and "go on".

Example 2

words = ["ab","ba","cat"]phrases = ["ab ab","ab ba cat"]return = [4,4]

Each position chooses on its own, even when the same word appears twice.

  • "ab ab" gives "ab ab", "ab ba", "ba ab", and "ba ba", so the count is 2 * 2 = 4.
  • "ab ba cat" gives 2 * 2 * 1 = 4, because cat has only itself.

Example 3

words = ["aab","aba","abb"]phrases = ["aab","abb","aba abb"]return = [2,1,2]

Anagrams must use each letter the same number of times. aab and aba are anagrams, but abb is not an anagram of them even though it uses the same two letters.

  • "aab" has 2 choices.
  • "abb" has 1 choice.
  • "aba abb" has 2 * 1 = 2 choices.

Constraints

  • 1 <= words.length <= 2000
  • 1 <= words[i].length <= 20
  • words[i] contains only lowercase English letters.
  • All strings in words are different.
  • 1 <= phrases.length <= 500
  • Each phrases[i] has 1 to 20 words, separated by single spaces, with no space at the start or end.
  • Every word in a phrase appears in words.
  • Each answer is at most 10^15.

More Wells Fargo problems

See Wells Fargo hiring insights
Saved
public long[] countPhrases(String[] words, String[] phrases) {
    // Write your solution here.
}
Checking account…