Minimum Length of Anagram Concatenation solution and explanation
9 more videos on this problem
3138. Minimum Length of Anagram Concatenation | Divisors & Factors | Hash MapAryan Mittal · 13:15 · 4K views
3138 Minimum Length of Anagram Concatenation || How to 🤔 in Interview || Divisors + Sorting + Map ✅Ayush Rao · 7:44 · 1K views
(C). LEETCODE 100283. Minimum Length of Anagram Concatenation | LEETCODE weekly-contest-396 SolutionJUST CODE · 0:51 · 827 views
3138. Minimum Length of Anagram Concatenation (Leetcode Medium)Programming Live with Larry · 17:59 · 498 views
Weekly contest 396 | Problem B solved | Minimum Length of Anagram Concatenationkhasanm · 0:16 · 473 views
Minimum Length of Anagram Concatenation (LeetCode 3138) (Weekly Contest 396) (Anagrams)CodeWithARB · 23:47 · 387 views
Leetcode Weekly Contest 396 || 100283. Minimum Length of Anagram Concatenation || Q.3 #contest #codeEzy Codes · 0:44 · 376 views
Leetcode Weekly Contest 396 Analysis | C. Minimum Length of Anagram ConcatenationTech Pe Charcha with Dpwala · 10:10 · 150 views
3138. Minimum Length of Anagram Concatenation | String && Anagram | Map | Factors of a number |FAANGLeet's Code · 6:28 · 110 views
DECODEDSA#LEVELUP#CONTESTSOL#leetcode#challenge#LC3138. Minimum Length of Anagram ConcatenationDecode · 8:25 · 33 views
The problem
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.
Constraints:
1 <= s.length <= 105sconsist only of lowercase English letters.
Approach overview
Problem Overview: You are given a string s. The string is formed by concatenating multiple substrings that are all anagrams of the same base string. Your task is to compute the minimum possible length of that base string.
The key observation: if a base string t of length k exists, then s must be split into n / k segments. Every segment must contain the same character frequency as t, just in a different order.
Approach 1: Frequency Analysis and GCD Method (O(n) time, O(1) space)
This approach relies on counting how many times each character appears in the entire string. Suppose character c appears count[c] times. If the string is composed of m anagram blocks, then the base string must contain count[c] / m occurrences of that character. For this to work, m must divide every character count.
Compute the greatest common divisor (GCD) of all character frequencies. That GCD represents the maximum number of identical anagram blocks the string can be split into. The minimum base string length becomes the sum of count[c] / gcd for all characters. Implementation uses a simple frequency array or hash map from Hash Table counting combined with a GCD calculation.
This works because each block must share identical frequency proportions. By normalizing counts with the GCD, you derive the smallest possible frequency profile that can repeat to generate the entire string.
Approach 2: Divisibility and Modular Arithmetic Analysis (O(n * d) time, O(1) space)
This method explicitly tests candidate base lengths. Let n be the length of the string. Any valid base length must divide n. For each divisor k, treat the first k characters as the frequency template. Then iterate through the string in blocks of size k, counting characters and checking if each block is an anagram of the template.
Character frequency comparisons can be implemented with arrays or counters from Counting. If all segments match, k is a valid answer. The smallest valid k is the minimum base length.
This approach is more explicit and easier to reason about during debugging. However, it performs repeated scans of the string and therefore runs slower than the GCD trick in worst cases.
Recommended for interviews: The GCD-based frequency analysis is the optimal approach and runs in O(n). Interviewers often expect you to recognize that anagram blocks imply proportional frequency counts across the entire string. Showing the divisor-check method first demonstrates clear reasoning, but the GCD insight shows stronger algorithmic intuition.
Approach 1: Frequency Analysis and GCD Method
This approach involves calculating the frequency of each character in the string s. By computing the greatest common divisor (GCD) of these frequencies, we can determine the minimum length of the original string t, because t should be such that each anagram formed from it can be repeated equal times to form s. The GCD gives us the maximum number of times the anagram can be repeated evenly across all character types.
from math import gcd
from collections import Counter
def min_length_of_t(s):
freq = Counter(s)
values = freq.values()
result = 0
for value in values:
result = gcd(result, value)
return result
# Testing the function
s = "abba"
print(min_length_of_t(s)) # Output: 2import java.util.HashMap;
public class AnagramConcatenation {
public static int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
public static int minLengthOfT(String s) {
HashMap<Character, Integer> freq = new HashMap<>();
for (char c : s.toCharArray()) {
freq.put(c, freq.getOrDefault(c, 0) + 1);
}
int result = 0;
for (int value : freq.values()) {
result = gcd(result, value);
}
return result;
}
public static void main(String[] args) {
String s = "abba";
System.out.println(minLengthOfT(s)); // Output: 2
}
}#include <iostream>
#include <unordered_map>
#include <numeric>
using namespace std;
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
int minLengthOfT(const string& s) {
unordered_map<char, int> freq;
for (const char& c : s) {
freq[c]++;
}
int result = 0;
for (const auto& pair : freq) {
result = gcd(result, pair.second);
}
return result;
}
// Testing the function
int main() {
string s = "abba";
cout << minLengthOfT(s) << endl; // Output: 2
return 0;
}function gcd(a, b) {
if (b == 0) return a;
return gcd(b, a % b);
}
function minLengthOfT(s) {
const freq = {};
for (const char of s) {
freq[char] = (freq[char] || 0) + 1;
}
let result = 0;
for (const value of Object.values(freq)) {
result = gcd(result, value);
}
return result;
}
// Testing the function
const s = "abba";
console.log(minLengthOfT(s)); // Output: 2using System;
using System.Collections.Generic;
class AnagramConcatenation {
static int GCD(int a, int b) {
if (b == 0) return a;
return GCD(b, a % b);
}
static int MinLengthOfT(string s) {
Dictionary<char, int> freq = new Dictionary<char, int>();
foreach (char c in s) {
if (freq.ContainsKey(c)) {
freq[c]++;
} else {
freq[c] = 1;
}
}
int result = 0;
foreach (int value in freq.Values) {
result = GCD(result, value);
}
return result;
}
static void Main() {
string s = "abba";
Console.WriteLine(MinLengthOfT(s)); // Output: 2
}
}We utilize the Python Counter to calculate the frequency of each character in s. Using the math.gcd function, we iteratively calculate the GCD of all character frequencies. This gives us the smallest possible length of t.
Time Complexity: O(n), where n is the length of the string s due to character counting.
Space Complexity: O(1), assuming only a constant number of English lowercase characters.
Approach 2: Divisibility and Modular Arithmetic Analysis
In this approach, we analyze how different counts of characters can be evenly divided to possibly rearrange into equal-sized parts forming the string s. This involves checking divisibility conditions and if all the character counts align to a common modularity that suggests a potential original t length. Essentially, we check if a string part can be divided in a way where each anagram fit the same pattern.
from collections import Counter
# Helper function to compute gcd using Euclidean algorithm
from math import gcd
def min_length_of_t_modular(s):
freq = Counter(s)
total_length = len(s)
max_gcd = 1
for k in range(1, total_length + 1):
if total_length % k == 0:
gcd_check = all(v % k == 0 for v in freq.values())
if gcd_check:
max_gcd = k
return max_gcd
# Testing the function
s = "abba"
print(min_length_of_t_modular(s)) # Output: 2function minLengthOfTModular(s) {
const freq = {};
const n = s.length;
let maxGCD = 1;
// Count characters frequency
for (const char of s) {
freq[char] = (freq[char] || 0) + 1;
}
for (let k = 1; k <= n; k++) {
if (n % k === 0) {
const gcdCheck = Object.values(freq).every(v => v % k === 0);
if (gcdCheck) {
maxGCD = k;
}
}
}
return maxGCD;
}
// Testing the function
const s = "abba";
console.log(minLengthOfTModular(s)); // Output: 2In this Python code, we calculate the maximum divisor k of a string that satisfies a condition where character frequencies modulo k equal zero, indicating each character fits perfectly into parts of size k. This is verified iteratively up to the length of s, providing our minimum t length.
Time Complexity: O(n * sqrt(n)) due to divisibility checks for each divisor.
Space Complexity: O(1), as additional storage is minimal.
Approach 3: Enumeration
Based on the problem description, the length of string t must be a factor of the length of string s. We can enumerate the length k of string t from small to large, and then check if it meets the requirements of the problem. If it does, we return. Thus, the problem is transformed into how to check whether the length k of string t meets the requirements.
First, we count the occurrence of each character in string s and record it in an array or hash table cnt.
Next, we define a function check(k) to check whether the length k of string t meets the requirements. We can traverse string s, taking a substring of length k each time, and then count the occurrence of each character. If the occurrence of each character multiplied by \frac{n}{k} does not equal the value in cnt, then return false. If all checks pass by the end of the traversal, return true.
The time complexity is O(n times A), where n is the length of string s, and A is the number of factors of n. The space complexity is O(|\Sigma|), where \Sigma is the character set, which in this case is the set of lowercase letters.
function minAnagramLength(s: string): number {
const n = s.length;
const cnt: Record<string, number> = {};
for (let i = 0; i < n; i++) {
cnt[s[i]] = (cnt[s[i]] || 0) + 1;
}
const check = (k: number): boolean => {
for (let i = 0; i < n; i += k) {
const cnt1: Record<string, number> = {};
for (let j = i; j < i + k; j++) {
cnt1[s[j]] = (cnt1[s[j]] || 0) + 1;
}
for (const [c, v] of Object.entries(cnt)) {
if (cnt1[c] * ((n / k) | 0) !== v) {
return false;
}
}
}
return true;
};
for (let i = 1; ; ++i) {
if (n % i === 0 && check(i)) {
return i;
}
}
}func minAnagramLength(s string) int {
n := len(s)
cnt := [26]int{}
for _, c := range s {
cnt[c-'a']++
}
check := func(k int) bool {
for i := 0; i < n; i += k {
cnt1 := [26]int{}
for j := i; j < i+k; j++ {
cnt1[s[j]-'a']++
}
for j, v := range cnt {
if cnt1[j]*(n/k) != v {
return false
}
}
}
return true
}
for i := 1; ; i++ {
if n%i == 0 && check(i) {
return i
}
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Frequency Analysis and GCD Method | Time Complexity: O(n), where n is the length of the string Space Complexity: O(1), assuming only a constant number of English lowercase characters. |
| Divisibility and Modular Arithmetic Analysis | Time Complexity: O(n * sqrt(n)) due to divisibility checks for each divisor. Space Complexity: O(1), as additional storage is minimal. |
| Enumeration | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Frequency Analysis and GCD Method | O(n) | O(1) | Best general solution. Uses global frequency counts to compute the minimal base pattern directly. |
| Divisibility and Modular Arithmetic Analysis | O(n * d) | O(1) | Useful for reasoning or debugging. Explicitly checks each valid segment length divisor. |
Frequently asked questions
Is Minimum Length of Anagram Concatenation easy or hard?
Minimum Length of Anagram Concatenation is rated Medium because it requires recognizing the relationship between anagram blocks and frequency ratios. The brute-force divisor approach is straightforward, but discovering the GCD optimization requires deeper insight into counting and number theory.
Minimum Length of Anagram Concatenation Python/Java solution
Most implementations use a frequency array and a GCD function. Python solutions typically rely on collections.Counter and math.gcd, while Java implementations use an int[26] array and iterative GCD computation. Both versions achieve O(n) time complexity.
How to solve Minimum Length of Anagram Concatenation in O(n)?
Count the frequency of each character in the string and compute the GCD of all counts. This GCD represents the number of anagram blocks the string can be divided into. Divide each frequency by the GCD and sum them to get the minimal base string length. The entire computation requires only a single pass over the string.
What is the best approach for Minimum Length of Anagram Concatenation?
The most efficient approach uses character frequency counting and the greatest common divisor (GCD) of all counts. If the string is composed of multiple anagram blocks, each block must maintain the same frequency ratio. Computing the GCD normalizes these counts and directly yields the smallest base string length. This solution runs in O(n) time with constant extra space.
Is Minimum Length of Anagram Concatenation asked at Google/Amazon/Meta?
Problems involving anagrams, frequency counting, and GCD patterns frequently appear in interviews at companies like Amazon, Google, and Meta. Variations often test your ability to combine hash maps with mathematical insights such as divisibility or greatest common divisor calculations.
What data structure is used in Minimum Length of Anagram Concatenation?
The primary data structure is a frequency map or fixed-size array used for character counting. This structure tracks how many times each letter appears in the string. The counts are then processed with a GCD calculation to determine the smallest repeating anagram block.
What is the time complexity of Minimum Length of Anagram Concatenation?
The optimal solution runs in O(n) time where n is the length of the string. You scan the string once to compute character frequencies and then calculate the GCD across those counts. Space complexity is O(1) because the alphabet size is fixed (typically 26 lowercase letters).
