Beats 100% in time and memory, the fastest solution
Approach\nTo get the number of anagrams of the entire string, we need to calculate the number of anagrams of each word and multiply them.\nTo calculate the numb
# Approach\nTo get the number of anagrams of the entire string, we need to calculate the number of anagrams of each word and multiply them.\nTo calculate the number of anagrams of one particular word, we can use the multinomial coefficient:\n![image.png](https://assets.leetcode.com/users/images/0b515ece-848c-457f-8eed-21f5cb0342ef_1707778488.838519.png)\nwhere $$n$$ - length of the word and $$k_i$$ - number of times the i-th letter has occurred in a word.\nCalculating this value directly in Go is quite difficult (as in many other languages).\nKnowing that we need to give an answer modulo $$10^9+7$$ we can make some optimizations:\nWe can use this\n![image.png](https://assets.leetcode.com/users/images/bc5e2352-8b2f-49d3-b0ba-70ba7193df81_1707779045.1994965.png)\nand this\n![image.png](https://assets.leetcode.com/users/images/0a78da7e-2447-4921-aead-c67270ea63ba_1707779080.2598438.png)\nwhere $$m$$ is a prime number, to translate the problem of multiplying large numbers to the problem of exponentiation, because $$10^9+7$$ is a prime number. \nAnd in order to quickly raise a number to a large power, we can use binary exponentiation\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n + w * log(10^9+7))$$, where $$w$$ - amount of words\nAs $$log(10^9+7)$$ is a constant and $$w < n$$, we can say that time complexity is $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfunc countAnagrams(s string) int {\n\tvar mod int64 = 1e9 + 7\n\tfactorials := make([]int64, len(s) + 1)\n\tfactorials[0] = 1\n\tfor i := 1; i <= len(s); i++ {\n\t\tfactorials[i] = (factorials[i-1] * int64(i)) % mod\n\t}\n\tvar pow func(val, p int64) int64\n\tpow = func(val, p int64) int64 {\n\t\tif p == 1 {\n\t\t\treturn val\n\t\t}\n\t\tif p%2 == 0 {\n\t\t\ttemp := pow(val, p/2)\n\t\t\treturn (temp * temp) % mod\n\t\t} else {\n\t\t\treturn (pow(val, p-1) * val) % mod\n\t\t}\n\t}\n\tcountAnagramsForWord := func(word string) int64 {\n\t\tcount := [26]int{}\n\t\tfor _, c := range word {\n\t\t\tcount[c-\'a\']++\n\t\t}\n\t\tn := len(word)\n\t\tresult := factorials[n]\n\t\tfor _, c := range count {\n\t\t\tresult = (result * pow(factorials[c], mod-2)) % mod\n\t\t}\n\t\treturn result\n\t}\n\tvar result int64 = 1\n\twords := strings.Fields(s)\n\tfor _, word := range words {\n\t\tresult = (result * countAnagramsForWord(word)) % mod\n\t}\n\treturn int(result)\n}\n```
['Go']