1347. Minimum Number of Steps to Make Two Strings Anagram - Detailed Explanation

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

Problem Statement

Given two strings s and t of equal length consisting of lowercase English letters, the goal is to make t an anagram of s by replacing characters in t. In one step, you can choose any character from t and change it to any other lowercase letter. You need to return the minimum number of such steps required so that t becomes an anagram of s.

Examples

Example 1

  • Input: s = "bab", t = "aba"
  • Output: 1
  • Explanation:
    • Frequency in s: {'b': 2, 'a': 1}
    • Frequency in t: {'a': 2, 'b': 1}
    • In t, there is one extra 'a' compared to s. Changing that extra 'a' to 'b' makes t an anagram of s.

Example 2

  • Input: s = "leetcode", t = "practice"
  • Output: 4
  • Explanation:
    • Frequency in s: {'l': 1, 'e': 3, 't': 1, 'c': 1, 'o': 1, 'd': 1}
    • Frequency in t: {'p': 1, 'r': 1, 'a': 1, 'c': 2, 't': 1, 'i': 1, 'e': 1}
    • In t, there is an extra 'c' (one extra occurrence) and extra occurrences of letters that do not appear in s (like 'p', 'r', 'a', and 'i').
    • Replacing these extra characters (a total of 4 changes) will make t an anagram of s.

Example 3

  • Input: s = "anagram", t = "mangaar"
  • Output: 0
  • Explanation:
    • Both strings have the same frequency of each character, meaning t is already an anagram of s. No changes are needed.

Constraints

  • The lengths of s and t are equal.
  • Both s and t consist of lowercase English letters.

Hints

  1. Frequency Counting: An anagram requires that both strings have identical character frequencies. Consider counting how many times each character appears in both strings.

  2. Focus on Surplus: Since you are only allowed to change characters in t, identify which characters in t occur more times than in s. The sum of these excess counts will be the minimum number of steps needed.

Approach 1: Counting Frequencies (Optimal Solution)

Explanation

  1. Count Frequencies:

    • Use an array (or hash map) of size 26 (one for each lowercase letter) to count the occurrences in s and t.
  2. Determine Excess Characters:

    • For every character, if t contains more instances than s, the extra characters need to be replaced.
    • Calculate the difference:
      • For character ch, if count_t[ch] > count_s[ch], then count_t[ch] - count_s[ch] is the number of steps required for that character.
  3. Sum the Differences:

    • The total minimum number of steps is the sum of these differences over all characters.

Visual Example (Example 1: s = "bab", t = "aba")

  • Step 1: Count frequencies
    • s: {'b': 2, 'a': 1}
    • t: {'a': 2, 'b': 1}
  • Step 2: Compare counts for each letter
    • For 'a': t has 2 and s has 1 → excess = 1
    • For 'b': t has 1 and s has 2 → no excess (ignore negative differences)
  • Step 3: Total steps = 1

Code in Python

Below is the Python implementation of the optimal solution using frequency counting.

Python3
Python3

. . . .

Code in Java

Below is the Java implementation using a similar frequency counting approach.

Java
Java

. . . .

Complexity Analysis

  • Time Complexity: O(n + 26) where n is the length of the strings. Counting the frequencies takes O(n) and comparing the 26 letters takes constant time.

  • Space Complexity: O(1) since the frequency arrays always have a fixed size of 26.

Step-by-Step Walkthrough

  1. Initialization:

    • Create two arrays of size 26 to hold character counts for s and t.
  2. Frequency Count:

    • Iterate over string s and update its frequency array.
    • Iterate over string t and update its frequency array.
  3. Comparing Frequencies:

    • For each index corresponding to a letter, check if the frequency in t is greater than that in s.
    • If yes, add the difference to the step count.
  4. Result:

    • Return the sum of differences as the minimum number of steps required.

Common Mistakes

  • Misinterpreting the Problem:

    • Attempting to change characters in both s and t rather than only modifying t.
  • Overcomplicating the Logic:

    • Using sorting or more complex data structures when simple frequency counting is sufficient.
  • Ignoring Edge Cases:

    • Not handling cases where the strings are already anagrams (result should be 0).

Edge Cases

  • Already Anagrams: When s and t have the same frequency for all characters, no steps are needed.

  • Completely Different Characters: When t contains none of the characters from s, all characters in t will need to be replaced.

Alternative Variations

  • Operations on Both Strings:

    • A variation might allow modifications on both s and t to make them anagrams. In such cases, you would need to consider the total absolute difference in counts and divide by 2.
  • Making Two Strings Palindromic:

    • Another variation could involve making two strings palindromic by modifying characters, which introduces a different set of constraints and strategies.
TAGS
leetcode
CONTRIBUTOR
Design Gurus Team
-

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
Related Courses
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
Image
One-Stop Portal For Tech Interviews.
Copyright © 2025 Design Gurus, LLC. All rights reserved.
;