KatInterview

Verify Anagram Coverage for All Contiguous Substrings

StringsAuto-graded · 24 test cases
MediumAuto-gradedStringsanagramsprefix-sumhashing

Last updated

Tests whether every contiguous substring of length 3 or more in a given string can be rearranged to match some dictionary word.

You are given a string text consisting only of letters, and a list of strings word_list representing a collection of valid words.

Determine whether every contiguous substring of text whose length is 3 or greater is an anagram of at least one word in word_list. Return True if so, or False otherwise.

Two strings are anagrams when they contain exactly the same multiset of characters, i.e., the same letter at every position has identical counts. For instance, "act" and "cat" are anagrams.

A substring is a contiguous slice text[i:j] for indices i < j. You must check all such slices where j - i >= 3.

If text has fewer than 3 characters, there are no qualifying substrings, so the answer is True.

Characters are compared as given. Do not perform any case folding; uppercase and lowercase letters are distinct.

Constraints:

  • text consists only of alphabetic characters (a-z, A-Z).
  • word_list may contain any number of strings, each consisting of alphabetic characters.
  • 0 <= len(text) <= 10^5
  • 0 <= len(word_list) <= 10^5
  • The total number of characters across word_list is at most 10^6.

Examples

Example 1

Input: check_all_anagram_substrings('act', ['cat'])

Output: True

Example 2

Input: check_all_anagram_substrings('abcd', ['abc', 'bcd', 'dcba'])

Output: True

Example 3

Input: check_all_anagram_substrings('abcd', ['abc', 'bcd'])

Output: False

Example 4

Input: check_all_anagram_substrings('aab', ['baa'])

Output: True

Hints

Hint 1

Two strings are anagrams iff their character-count vectors are identical. Build a set of canonical keys from the dictionary rather than generating permutations.

Hint 2

Use prefix sums of packed count vectors so that the signature of any substring is computed by subtracting two prefix values in O(1).

Hint 3

Before the main loop, verify that the dictionary contains at least one word of every length from 3 to len(text). A missing length means an immediate False, which prunes large inputs quickly.