Taro Logo

Minimum Length of Anagram Concatenation

Medium
Asked by:
Turing
UKG
4 views
Topics:
Strings

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 <= 105
  • s consist only of lowercase English letters.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What character set does the string s consist of? Are we only dealing with lowercase English letters, or could it include uppercase letters, digits, or Unicode characters?
  2. Is it guaranteed that the input string s is always a valid concatenation of an anagram of some base string, or do we need to handle cases where s cannot be formed this way?
  3. What are the constraints on the length of the string s (e.g., maximum length of $N$) so I can gauge the expected time and space complexity?
  4. Could the base string simply be the entire string s itself if no smaller repeating anagram unit exists?
  5. Does the base string need to be a contiguous substring of s, or can its characters be gathered from non-contiguous parts of the concatenated instances?

Brute Force Solution

Approach

To find the shortest repeating building block of a scrambled word puzzle, the brute force approach tests every possible starting size from smallest to largest. For each size we check, we see if the entire full message can be neatly divided into matching chunks made of those exact same letters.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first letter of the message and consider it as a tiny test chunk.
  2. Check if the entire remaining message is made up of exact rearrangements of just that single letter chunk.
  3. If it matches completely, you have found your answer, so stop and celebrate.
  4. If it does not match, take the first two letters as your next test chunk and check the whole message again to see if it can be chopped into identical pieces of that size.
  5. Continue this process by slowly growing your test chunk by one letter at a time.
  6. Test every single possible chunk size until you find the very first one that can successfully divide the whole message into matching rearranged pieces.

Code Implementation

def min_anagram_length(message):    # Test every possible chunk size starting from the smallest possible length up to the full string    for chunk_length in range(1, len(message) + 1):        if len(message) % chunk_length != 0:            continue        base_chunk = message[:chunk_length]        base_counts = {char: base_chunk.count(char) for char in set(base_chunk)}        is_valid_pattern = True        # Verify if all subsequent chunks are valid anagrams of the base chunk        for index in range(chunk_length, len(message), chunk_length):            current_chunk = message[index:index + chunk_length]            current_counts = {char: current_chunk.count(char) for char in set(current_chunk)}            if current_counts != base_counts:                is_valid_pattern = False                break        # Stop immediately once we find the smallest chunk size that successfully divides the message        if is_valid_pattern:            return chunk_length    return len(message)

Big(O) Analysis

Time Complexity
O(n²) – To analyze the runtime, let n be the length of the message. We iterate through possible chunk sizes from 1 up to n, and for each tested size that evenly divides n, we verify all chunks by comparing their character frequencies. In the worst case, we test up to n different chunk sizes, and for each size we process all n characters of the message to check for valid anagram partitions. This leads to approximately n * n/2 operations, which simplifies to O(n²).
Space Complexity
O(k) – To verify if the message can be divided into identical rearranged pieces of a chosen test chunk of size k, we must track letter counts for both the chunk and the sub-segments. Since the alphabet size is constant, the frequency maps or arrays require a fixed maximum auxiliary space bounded by the number of unique characters rather than the total input length N. As we test chunk sizes ranging from 1 up to N, the extra memory used to store these character counts remains completely constant. Therefore, the overall auxiliary space complexity simplifies to O(1) in terms of the string length N.

Optimal Solution

Approach

To find the shortest possible building block that repeats to form the given sequence, we realize that the length of the final sequence must be cleanly divisible by the length of this repeating block. By testing potential block sizes starting from the smallest possible divisor, we can quickly find the exact length where all smaller chunks match the exact same letter counts.

Here's how the algorithm would work step-by-step:

  1. Measure the total length of the entire sequence of letters provided.
  2. Find all the numbers that can divide the total length evenly, starting with the smallest possible divisor.
  3. Test each potential divisor size by cutting the sequence into chunks of that exact size.
  4. Compare the internal counts of each letter within the first chunk against every other chunk.
  5. If every single chunk contains the exact same amount and type of letters, then that chunk size is our answer.
  6. If the counts do not match, move on to the next larger divisor size and repeat the comparison.
  7. Stop as soon as you find the first chunk size that satisfies the matching condition, as this will guarantee the minimum length.

Code Implementation

def min_anagram_length(input_sequence):
    total_length = len(input_sequence)

    # We test divisors from smallest to largest to guarantee finding the minimum valid block size first.
    for potential_divisor in range(1, total_length + 1):
        if total_length % potential_divisor == 0:
            chunk_size = potential_divisor
            reference_counts = {}
            
            for character in input_sequence[0:chunk_size]:
                reference_counts[character] = reference_counts.get(character, 0) + 1

            is_valid_block = True

            # We compare every subsequent chunk against the first chunk to check for identical anagram counts.
            for chunk_start in range(chunk_size, total_length, chunk_size):
                current_counts = {}
                current_chunk = input_sequence[chunk_start:chunk_start + chunk_size]
                
                for character in current_chunk:
                    current_counts[character] = current_counts.get(character, 0) + 1

                if current_counts != reference_counts:
                    is_valid_block = False
                    break

            # Stopping at the first valid size guarantees the absolute minimum repeating block length.
            if is_valid_block:
                return chunk_size

    return total_length

Big(O) Analysis

Time Complexity
O(n * sqrt(n)) – Let n be the length of the string. We iterate through all possible divisors of n, which takes O(sqrt(n)) time. For each valid divisor representing a chunk size, we compare letter counts across n / k chunks, where each chunk takes O(k) time to count and compare, resulting in O(n) work per divisor test. Multiplying the O(sqrt(n)) divisors by the O(n) checking cost per divisor gives approximately n * sqrt(n) total operations in the worst case. This simplifies to a Big O time complexity of O(n * sqrt(n)).
Space Complexity
O(1) – The space complexity is constant because the frequency counting uses fixed-size arrays or hash maps limited to the 26 lowercase English letters. The chunks and divisors require only a few primitive integer variables to track lengths and indices. No data structures scale with the input size N, meaning the extra memory remains strictly bounded regardless of how long the sequence is.

Edge Cases

String of length one
How to Handle:
The algorithm should immediately return one since a single character string is its own base anagram.
String formed by identical characters
How to Handle:
The frequency check will determine that the base length is one because all characters are the same.
String length is a prime number
How to Handle:
The divisor loop correctly checks only up to the square root or factors, eventually falling back to the full length if no smaller base divides it evenly.
Large strings approaching the maximum constraints
How to Handle:
An O(N) frequency counting and divisor checking approach ensures the solution executes well within time limits without exceeding memory.
Base string appears only once
How to Handle:
Since the string itself is a single instance of the base anagram, the minimum length will equal the total length of the input string.
Base string repeats a very high number of times with uniform character distribution
How to Handle:
The greatest common divisor of all character counts will correctly scale down to the shortest possible base length.
Inputs containing non-ASCII or special Unicode characters
How to Handle:
Using a hash map instead of a fixed size array for character frequencies ensures proper handling of extended character sets.