Minimum Length of Anagram Concatenation Problem
Description
LeetCode Problem 3138.
You are given a string s, which is known to be a concatenation of anagrams of some string t.
Return the minimum possible length of the string t.
An anagram is formed by rearranging the letters of a string. For example, "aab", "aba", and, "baa" are anagrams of "aab".
Example 1:
Input: s = "abba"
Output: 2
Explanation:
One possible string t could be "ba".
Example 2:
Input: s = "cdef"
Output: 4
Explanation:
One possible string t could be "cdef", notice that t can be equal to s.
Example 2:
Input: s = "abcbcacabbaccba"
Output: 3
Constraints:
1 <= s.length <= 10^5sconsist only of lowercase English letters.
Solution
Approach: Enumeration
The length k of t must divide n, the length of s. Try the divisors in increasing order and return the first one that works.
Count the letters of s once. For a candidate k, split s into n / k blocks and count the letters of each block; the block is an anagram of the same t for all blocks exactly when every letter count in the block equals the total count divided by n / k.
Complexity: time O(n * A), space O(26), where A is the number of divisors of n.
from collections import Counter
class Solution:
def minAnagramLength(self, s: str) -> int:
def check(k: int) -> bool:
for i in range(0, n, k):
cnt1 = Counter(s[i : i + k])
for c, v in cnt.items():
if cnt1[c] * (n // k) != v:
return False
return True
cnt = Counter(s)
n = len(s)
for i in range(1, n + 1):
if n % i == 0 and check(i):
return i