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
Count frequencies in s, decrement for t. Sum absolute values of counts and divide by 2.
Time O(n), Space 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.
