Taro Logo

Minimum Number of Steps to Make Two Strings Anagram

#17 Most AskedMedium
0 views
Topics:
ArraysStrings

You are given two strings of the same length s and t. In one step you can choose any character of t and replace it with another character.

Return the minimum number of steps to make t an anagram of s.

An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.

Example 1:

Input: s = "bab", t = "aba"
Output: 1
Explanation: Replace the first 'a' in t with b, t = "bba" which is anagram of s.

Example 2:

Input: s = "leetcode", t = "practice"
Output: 5
Explanation: Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s.

Example 3:

Input: s = "anagram", t = "mangaar"
Output: 0
Explanation: "anagram" and "mangaar" are anagrams. 

Constraints:

  • 1 <= s.length <= 5 * 104
  • s.length == t.length
  • s and t consist of lowercase English letters only.

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. Are the strings `s` and `t` guaranteed to contain only lowercase English letters?
  2. Can we assume that `s` and `t` will always be of the exact same length?
  3. What should be returned if `s` and `t` are already identical anagrams?
  4. Are we strictly limited to replacing characters in `t`, or could operations like deletions or insertions also be considered?
  5. Is there any memory constraint regarding the alphabet size or auxiliary data structures we can use?

Brute Force Solution

Approach

To figure out the minimum steps to make two words anagrams using a brute force method, you would exhaustively explore every possible way to swap or change letters until both words contain the exact same letters in some order. Since this is the most exhaustive approach, you basically test all potential modifications to see which one gets the job done with the fewest changes.

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

  1. Start by looking at the first word and picking any letter inside it.
  2. Consider every single option to replace that chosen letter with any other letter of the alphabet, or imagine removing it entirely.
  3. For every single one of those changes, compare the modified first word against the second word to see if they are now anagrams of each other.
  4. If they do not match yet, repeat the process by making another change to the already modified word, testing all possible next letter swaps.
  5. Keep track of how many total changes you had to make for this specific sequence of actions.
  6. Systematically try every other possible starting change and repeat the entire path of modifications until you have explored every conceivable way to alter the first word.
  7. Finally, look back at all the successful paths you found and pick the one that required the smallest total number of changes.

Code Implementation

def min_steps(first_string, second_string):
    from collections import deque
    alphabet_letters = 'abcdefghijklmnopqrstuvwxyz'
    queue_for_search = deque([(first_string, 0)])
    visited_states = {first_string}

    # We use a breadth-first search to guarantee finding the shortest modification path first.
    while queue_for_search:
        current_word, current_steps = queue_for_search.popleft()
        
        if sorted(current_word) == sorted(second_string):
            return current_steps

        # Generate all possible single-character modifications to explore every branch thoroughly.
        for index in range(len(current_word)):
            for replacement in alphabet_letters:
                modified_word = current_word[:index] + replacement + current_word[index + 1:]
                
                if modified_word not in visited_states:
                    visited_states.add(modified_word)
                    queue_for_search.append((modified_word, current_steps + 1))

    return 0

Big(O) Analysis

Time Complexity
O(26^n) – For each character in the input string of length n, we systematically explore 26 possible letter replacements at every single step of modification. Since we recursively test all these variations and branch out for each remaining position until the string length is exhausted, the decision tree grows exponentially. This leads to approximately 26 raised to the power of n total exploration paths, which simplifies to the exponential time complexity of O(26^n).
Space Complexity
O(1) – The brute force exploration requires maintaining state variables to track the modified first word and recursion stack frames for every possible substitution path. Since the alphabet size is strictly fixed at 26 English letters, the maximum recursion depth and the number of distinct character replacement options at each step are bounded by constant limits. As the input string length N increases, these state tracking mechanisms and call stacks do not scale with N. Therefore, the extra memory used remains constant, resulting in O(1) auxiliary space complexity.

Optimal Solution

Approach

To find the minimum number of steps to make two words anagrams, we need to focus on what letters are missing or extra. By simply counting how many times each letter appears in both words, we can easily figure out how many changes are needed.

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

  1. Count how many times each letter appears in the first word.
  2. Count how many times each letter appears in the second word.
  3. Compare the two sets of counts to see which letters appear more often in the first word compared to the second.
  4. Add up all the shortages of letters from the comparison, because every missing letter represents a necessary change to match the other word.
  5. The total sum of these shortages gives you the final answer for the minimum number of steps required.

Code Implementation

def min_steps_to_anagram(first_word, second_word):

    # We count character frequencies to establish a baseline for comparison.
    first_word_counts = [0] * 26
    for character in first_word:
        first_word_counts[ord(character) - ord('a')] += 1

    second_word_counts = [0] * 26
    for character in second_word:
        second_word_counts[ord(character) - ord('a')] += 1

    # Summing shortages identifies exact character deficits between the two words.
    total_shortages = 0
    for alphabet_index in range(26):
        if first_word_counts[alphabet_index] > second_word_counts[alphabet_index]:
            total_shortages += first_word_counts[alphabet_index] - second_word_counts[alphabet_index]

    # Total shortages directly equate to the minimum steps required for anagram parity.
    return total_shortages

Big(O) Analysis

Time Complexity
O(n) – First, we iterate through both strings to count the frequency of each character, where n represents the length of the strings. Next, we iterate through the fixed alphabet size of 26 to compare the frequency counts and sum up the shortages. Since the alphabet size is a constant 26, the time required scales linearly with the input string length n. Ultimately, the total operations scale proportionally to n, which simplifies to O(n).
Space Complexity
O(1) – The auxiliary space is driven by a fixed-size frequency array of 26 integers to store character counts for the English alphabet. Because this data structure uses a constant amount of memory regardless of the input string length N, the space complexity remains strictly bounded. Consequently, the extra memory required does not grow with the input size, simplifying to a constant Big O notation.

Edge Cases

Strings are already exact anagrams of each other
How to Handle:
The frequency counts will completely balance out, and the algorithm correctly returns zero steps.
Strings share no common characters at all
How to Handle:
Every character in t must be replaced, so the algorithm will sum all frequencies and return the full string length.
Minimum length strings of size one with differing characters
How to Handle:
The frequency array handles single-character bounds properly and returns one replacement step.
Inputs contain only identical characters such as s equals aaa and t equals bbb
How to Handle:
The bucket counts will aggregate all occurrences into a single index and compute the difference efficiently.
Maximum constraint string lengths up to fifty thousand characters
How to Handle:
Using a fixed-size frequency array or hash map guarantees an optimal linear time complexity of O(n).
Characters are restricted to lowercase English letters only
How to Handle:
A fixed-size array of size twenty-six maps characters directly without needing complex hashing logic.
String t contains excess characters not present in s
How to Handle:
The counting logic only accumulates positive discrepancies for characters that exceed s frequencies.
0/17 completed