A word-game app wants to rate how "shuffly" a puzzle string is. It counts the pairs of pieces of the string that use exactly the same letters, the same number of times, in any order. Pieces at different positions count separately, even when their text is identical.
Write countAnagramPairs(s). A substring is identified by its start and end positions, so a string of length n has n(n + 1) / 2 substrings. Return the number of unordered pairs of different substrings that are anagrams of each other.
Rules:
Two substrings are anagrams when each letter appears the same number of times in both. They must therefore have the same length, but they may overlap.
s contains only lowercase letters a to z. An empty string returns 0. If s is not a string, or contains any other character, throw a TypeError.
Strings can be 500 letters long. Comparing every pair of substrings is about 20 million comparisons of up to 500 letters each and will not finish in time.
countAnagramPairs("abba"); // 4: a/a, b/b, ab/ba, abb/bbacountAnagramPairs("abcd"); // 0: every letter is differentcountAnagramPairs("cdcd"); // 5: c/c, d/d, cd/dc, cd/cd, dc/cdcountAnagramPairs("kkkk"); // 10
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
2
code listings
5
edge cases
What's inside
The full problem, with examples
Tests that check your solution
Step-by-step
Approach
Solution
Complexity
Edge cases
Follow-up questions
Card worldwide
UPI and net banking in India
One-time payment, nothing renews
Private, and saved in this browser as you type. All your notes are on My lists.