Verify Anagram Coverage for All Contiguous Substrings
StringsAuto-graded · 24 test casesLast 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:
textconsists only of alphabetic characters (a-z, A-Z).word_listmay contain any number of strings, each consisting of alphabetic characters.0 <= len(text) <= 10^50 <= len(word_list) <= 10^5- The total number of characters across
word_listis at most10^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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
The core insight is that two strings are anagrams if and only if their character-count vectors are identical. Rather than sorting each substring or generating permutations, we encode each count vector as a single integer and store dictionary words' signatures in a hash set. Then for each substring we compute its signature in O(1) via prefix sums and check membership in the set.
Encoding. Each character in the combined alphabet gets a fixed bit field. The field width is (n+1).bit_length() bits, which is enough to hold any count from 0 to n without overflowing into the next character's field. A string's signature is the sum of 1 << shift[char] for each character in it. Because fields never overflow, two strings produce the same integer if and only if they have identical count vectors — there are no collisions.
Prefix sums. We build prefix[k] as the packed count vector of text[0:k]. For a substring text[i:j], the signature is prefix[j] - prefix[i]. Since counts only grow along the prefix, every field in prefix[j] is at least as large as the corresponding field in prefix[i], so the subtraction is borrow-free at the field level and yields exactly the packed count vector of the substring.
Length pruning. Before the quadratic loop, we verify that the dictionary contains at least one word of every length from 3 through n. If any length is missing, no substring of that length can match, so we return False immediately. This bounds the effective input size by the dictionary's longest word, which in practice keeps inputs small.
Correctness. The encoding is exact (not a hash), so membership in the signature set is a perfect anagram test. Every substring of length >= 3 is checked, and a single failure means the universal condition fails. Words shorter than 3 or longer than n are discarded since they can never match a checked substring. The vacuous case (n < 3) returns True because there are no qualifying substrings.
Complexity. Let D be the total characters across word_list and let the alphabet have size sigma. Preprocessing the dictionary is O(D). Building the prefix array is O(n). The main loop checks O(n^2) substrings, each costing one subtraction and one hash lookup, giving O(n^2) time with a small constant. Space is O(D) for the signature set and O(n) for the prefix array.
from typing import List
def check_all_anagram_substrings(text: str, word_list: List[str]) -> bool:
n = len(text)
if n < 3:
return True
available_lengths = {len(w) for w in word_list}
if any(length not in available_lengths for length in range(3, n + 1)):
return False
usable = [w for w in word_list if 3 <= len(w) <= n]
alphabet = sorted(set(text).union(*(set(w) for w in usable)))
char_index = {ch: i for i, ch in enumerate(alphabet)}
bits = max(1, (n + 1).bit_length())
shift_for = [bits * char_index[ch] for ch in alphabet]
dict_sigs = set()
for w in usable:
sig = 0
for ch in w:
sig += 1 << shift_for[char_index[ch]]
dict_sigs.add(sig)
prefix = [0] * (n + 1)
for i, ch in enumerate(text):
prefix[i + 1] = prefix[i] + (1 << shift_for[char_index[ch]])
for start in range(n - 2):
for end in range(start + 3, n + 1):
if prefix[end] - prefix[start] not in dict_sigs:
return False
return True