Problem Description
Given a string s that is formed by concatenating several anagrams of an unknown string t, determine the minimum possible length of t.
Key Insights
- s is a concatenation of copies (reordered as anagrams) of t.
- For every letter that appears in s, its total frequency is a multiple of its frequency in t.
- Let x be the number of copies (chunks) in s, then for every letter c in s, frequency f(c) = (frequency in t) * x.
- To minimize the length of t, we need to maximize x, which must be a common divisor of all letter frequencies in s.
- Thus, the maximal x equals the greatest common divisor (gcd) of all nonzero frequency counts.
- The length of t is then computed as s.length / gcd.
Space and Time Complexity
Time Complexity: O(n) where n is the length of s (to count frequencies and compute gcd over a constant number of characters).
Space Complexity: O(1) since we only store frequency data for 26 possible lowercase letters.
Solution
We first count the frequency of each character in s using a hash table (or a fixed-size array of length 26). Next, we compute the gcd of all nonzero letter counts; this gcd represents the maximum number of anagram copies that can form s. The minimum possible length of t is then (s.length divided by this gcd). This approach leverages the fact that t's letter frequencies are scaled down versions of s's frequencies by the factor x (the number of chunks).