Minimum Steps to Make Two Strings Anagram
Given two equal-length strings, count the minimum steps to make t an anagram of s. In one step, you can change any character of t to any other character. Count the total excess characters in one string over the other and divide by 2.
This is a hash map frequency counting problem: count each character in both strings, sum the absolute differences, and divide by 2. Each excess character in one string needs to be changed to match the deficiency in the other.
This problem is a variant of the classic Valid Anagram problem and tests understanding of frequency difference calculations. The answer is always half the sum of absolute differences because each change fixes one excess in one string and one deficiency in the other.
Edge cases include identical strings (0 steps needed), completely different strings (n steps where n is the length), and single-character strings (0 if same, 1 if different). The frequency difference approach works for all cases.
This problem extends the concept of anagram checking by quantifying how far apart two strings are. The hash map approach naturally computes the per-character difference. Dividing by 2 accounts for the fact that each change reduces the difference for both strings simultaneously.
Example Input & Output
5 changes.
Already anagrams.
Change a to b.
Algorithm Flow
Solution Approach
Given two strings s and t, find the minimum number of steps to make them anagrams. In each step, you can change any character in either string. Count the frequency of each character in both strings. The number of steps is half the sum of absolute differences between the frequency arrays, or equivalently, the total characters minus twice the common character count.
Positive values in freq after subtracting t's counts represent characters in s that need to be changed. Each such excess character requires one step to transform into a character t needs.
Time complexity is O(n + m), space complexity is O(1).
Best Answers
import java.util.*;
class Solution {
public int solution(String s, String t) {
int[] counts = new int[26];
for (char ch : s.toCharArray()) counts[ch-'a']++;
for (char ch : t.toCharArray()) counts[ch-'a']--;
int steps = 0;
for (int c : counts) steps += Math.abs(c);
return steps/2;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
