Minimum Length of Anagram Concatenation - Problem

You are given a string s that represents a concatenation of multiple anagrams of some unknown string t. Your task is to find the minimum possible length of the original string t.

An anagram is formed by rearranging the letters of a string. For example, "aab", "aba", and "baa" are all anagrams of "aab".

Key insight: Since s is formed by concatenating anagrams of t, the length of t must be a divisor of the length of s. We need to find the smallest such divisor where each segment of that length in s contains the same character frequencies.

Example: If s = "abcabc", it could be two anagrams of t = "abc", so the answer is 3.

Input & Output

example_1.py โ€” Basic case
$ Input: s = "abcabc"
โ€บ Output: 3
๐Ÿ’ก Note: The string can be split into two anagrams of "abc": "abc" and "abc". Both segments have the same character frequencies (a:1, b:1, c:1), so the minimum length is 3.
example_2.py โ€” Multiple valid lengths
$ Input: s = "abcabcabcabc"
โ€บ Output: 3
๐Ÿ’ก Note: The string has length 12. Possible divisors are 1, 2, 3, 4, 6, 12. Length 3 works (four segments: "abc", "abc", "abc", "abc"), so we return 3 as the minimum.
example_3.py โ€” Single character
$ Input: s = "aaaa"
โ€บ Output: 1
๐Ÿ’ก Note: The string consists of the same character repeated. Each segment of length 1 contains the same character frequencies, so the minimum length is 1.

Constraints

  • 1 โ‰ค s.length โ‰ค 105
  • s consists of lowercase English letters only
  • The string s is guaranteed to be a concatenation of anagrams of some string t

Visualization

Tap to expand
abcabcPattern: abcEach arc segment contains same bead colors with same frequencies
Understanding the Visualization
1
Identify Constraints
The pattern length must divide the total length evenly
2
Generate Candidates
Find all divisors of the string length efficiently
3
Validate Patterns
Check if all segments have identical character frequencies
4
Return Minimum
The first valid divisor is our answer
Key Takeaway
๐ŸŽฏ Key Insight: The minimum anagram length must be a divisor of the total string length, and all segments of that length must contain identical character frequency distributions.
Asked in
Google 42 Amazon 38 Meta 29 Microsoft 24
48.6K Views
Medium Frequency
~18 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen