Loading content...
You are given two strings: a pattern string and a text string. Your task is to determine whether any rearrangement (anagram) of the pattern exists as a contiguous substring within the text.
An anagram of a string is another string that contains the exact same characters with the exact same frequencies, but potentially arranged in a different order. For example, "abc", "bca", and "cab" are all anagrams of each other.
Return true if the text contains at least one contiguous substring that is an anagram of the pattern. Return false otherwise.
Consider the pattern "ab" and the text "eidbaooo":
trueNow consider the pattern "ab" and the text "eidboaoo":
falseThe core insight is that you don't need to generate all permutations of the pattern (which would be factorial in complexity). Instead, two strings are anagrams if and only if they have identical character frequency distributions. This transforms the problem into efficiently comparing character frequencies across a sliding window.
pattern = "ab"
text = "eidbaooo"trueThe text contains the substring "ba" starting at index 3, which is an anagram of "ab". The characters 'b' and 'a' appear exactly once each in both strings, just in different orders.
pattern = "ab"
text = "eidboaoo"falseThere is no contiguous substring in the text that contains exactly one 'a' and one 'b' adjacent to each other. While both characters exist in the text, they never appear together as consecutive characters.
pattern = "abc"
text = "cbade"trueThe text contains the substring "cba" starting at index 0, which is an anagram of "abc". Both strings contain exactly one 'a', one 'b', and one 'c'.
Constraints