Skip to main content

Minimum Number of Steps to Make Two Strings Anagram - Solution & Explanation

MediumHash TableStringCounting13 min readAsked at: Amazon, Microsoft, Oracle +7
Practice this problem

Problem Statement

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.

Approach Overview

Problem Overview: You are given two strings s and t of the same length. In one step you can replace any character in t. The goal is to compute the minimum number of replacements required so that t becomes an anagram of s.

Approach 1: Sorting and Compare (O(n log n) time, O(n) space)

A straightforward way to reason about anagrams is sorting both strings. If two strings are anagrams, their sorted versions are identical. Sort s and t, then iterate through both arrays and count mismatched characters. Each mismatch indicates a character in t that must be replaced. Sorting dominates the runtime at O(n log n), while storing sorted arrays requires O(n) space. This approach works but wastes time doing full ordering when the problem only requires frequency comparison.

Approach 2: Frequency Count Method (O(n) time, O(1) space)

The optimal solution relies on counting character frequencies using a fixed-size array or hash map. Iterate through string s and increment counts for each character. Then iterate through t and decrement the corresponding counts. If a count becomes negative, it means t has more of that character than s, so a replacement is required. Increment the step counter in that case. Because the alphabet size is constant (26 lowercase letters), the frequency structure uses constant space. The entire algorithm runs in O(n) time with O(1) space.

This technique is common in problems involving anagrams or character balancing. The idea is to track the difference between character distributions rather than reconstructing the actual anagram. A simple integer array indexed by char - 'a' works well, though a hash table also works if the character set is larger.

Conceptually, you are computing how many characters in t exceed the available counts from s. Every extra occurrence forces a replacement. This makes the solution a classic counting pattern combined with efficient string traversal.

Recommended for interviews: The frequency count method. Interviewers expect you to recognize that anagrams depend only on character counts, not order. Mentioning a sorting approach first demonstrates baseline reasoning, but moving to the O(n) counting solution shows stronger algorithmic intuition and understanding of constant-space optimizations.

Approach 1: Frequency Count Method

In this method, we need to count the frequency of each character in strings s and t. We then calculate the number of changes required in t by comparing these frequencies. Specifically, for each character, if the frequency count in s is greater than in t, those are the extra characters needed in t. The total number of these extra characters across all characters gives the result.

This C code defines a function that calculates the difference in frequency of each character between the two strings. It uses an array of size 26 to store the frequency count of characters. The function iterates through the string s to increment the frequency and then through t to decrement. The remaining positive values in the array represent the total change needed.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), where n is the length of the strings (since they are of equal length).
Space Complexity: O(1), since the space required does not depend on the input size.

Try this approach in the editor →

Approach 2: Counting

We can use a hash table or an array cnt to count the occurrences of each character in the string s. Then, we traverse the string t. For each character, we decrement its count in cnt. If the decremented value is less than 0, it means that this character appears more times in the string t than in the string s. In this case, we need to replace this character and increment the answer by one.

After the traversal, we return the answer.

The time complexity is O(m + n), and the space complexity is O(|\Sigma|), where m and n are the lengths of the strings s and t, respectively, and |\Sigma| is the size of the character set. In this problem, the character set consists of lowercase letters, so |\Sigma| = 26.

Code

Python

Java

C++

Go

TypeScript

JavaScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Frequency Count Method

Time Complexity: O(n), where n is the length of the strings (since they are of equal length).
Space Complexity: O(1), since the space required does not depend on the input size.

Counting—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Sorting Both StringsO(n log n)O(n)Simple conceptual solution when constraints are small or when sorting utilities are already used.
Frequency Count (Hash Table / Array)O(n)O(1)Optimal approach for large strings. Best for interview settings and production code.

Video Solution

Leetcode 1347. Minimum Number of Steps to Make Two Strings Anagram • Fraz • 11,225 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Minimum Number of Steps to Make Two Strings Anagram easy or hard?
The problem is rated Medium because the key insight is recognizing that only frequency differences matter. Once you map characters to counts, the implementation becomes straightforward and runs in linear time.
Minimum Number of Steps to Make Two Strings Anagram Python/Java solution
Both Python and Java implementations follow the same idea: maintain a frequency array for characters in s, then iterate through t and reduce counts while counting excess characters. Python typically uses a list of size 26, while Java uses an int[26] array for constant-time updates.
How to solve Minimum Number of Steps to Make Two Strings Anagram in O(n)?
Create an integer array of size 26 to store character frequencies from string s. Iterate through s and increment counts. Then iterate through t and decrement counts; if a count becomes negative, increment the step counter because that character must be replaced. The traversal of both strings makes the algorithm O(n).
What is the best approach for Minimum Number of Steps to Make Two Strings Anagram?
The best approach uses frequency counting. Count characters in string s, then traverse string t and reduce those counts. Whenever a character in t exceeds the available count from s, you must replace it, so increment the step counter. This runs in O(n) time with O(1) space when using a fixed 26-length array.
Is Minimum Number of Steps to Make Two Strings Anagram asked at Google/Amazon/Meta?
Anagram and frequency-counting problems frequently appear in interviews at companies like Amazon, Google, and Meta. Variants of this problem test your understanding of hash maps, character counting, and linear-time string processing.
What data structure is used in Minimum Number of Steps to Make Two Strings Anagram?
The primary data structure is a frequency table, typically implemented as a fixed-size array of length 26 for lowercase letters. A hash map can also be used for more general character sets. The structure tracks the difference between character counts in the two strings.
What is the time complexity of Minimum Number of Steps to Make Two Strings Anagram?
The optimal solution runs in O(n) time where n is the string length. Each character of both strings is processed once using a frequency array. Space complexity is O(1) because the alphabet size (26 lowercase letters) is constant.

Ready to solve this problem?

Practice Minimum Number of Steps to Make Two Strings Anagram with our built-in code editor and test cases.

Practice on FleetCode