A word-puzzle app highlights every place in a block of text where the letters of a hidden word appear in some scrambled order. In "stop pots tops", the word "opts" is hidden three times: stop, pots and tops.
Write two functions that take strings text and pattern:
anagramStarts(text, pattern) returns, in increasing order, every index i where text.slice(i, i + pattern.length) is an anagram of pattern: the same characters with the same counts, in any order.
countAnagrams(text, pattern) returns how many such indexes there are.
Rules:
Treat each text[i] as one character. Comparison is exact: "A" and "a" are different, and spaces and punctuation are ordinary characters.
Matches may overlap, and each start index counts once: anagramStarts("abab", "ab") is [0, 1, 2].
If pattern is longer than text, there are no matches ([] and 0).
Throw a TypeError if text or pattern is not a string, and a RangeError if pattern is empty.
text can have 200,000 characters and pattern 100,000. Sorting or recounting every window costs O(n × m) and will not finish in time, so aim for O(n + m).
anagramStarts("stop pots tops", "opts"); // [0, 5, 10]anagramStarts("tealeatlate", "tea"); // [0, 4, 8]anagramStarts("abbaab", "aab"); // [2, 3]: "abb" has the right letters but the wrong countscountAnagrams("abab", "ab"); // 3countAnagrams("hi", "high"); // 0
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
2
code listings
6
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.