#1347
Minimum Number of Steps to Make Two Strings Anagram
MediumHash TableStringCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages frequency counting to determine how many characters need to be replaced in t to match the character counts in s. This is efficient and avoids unnecessary iterations.
⚙️
Algorithm
4 steps- 1Step 1: Create two frequency arrays for characters in s and t.
- 2Step 2: Count the frequency of each character in both strings.
- 3Step 3: For each character, calculate the difference in frequency between s and t. If t has fewer of a character than s, add that difference to the total steps needed.
- 4Step 4: Return the total number of steps.
solution.py12 lines
1def min_steps(s, t):
2 count_s = [0] * 26
3 count_t = [0] * 26
4 for char in s:
5 count_s[ord(char) - ord('a')] += 1
6 for char in t:
7 count_t[ord(char) - ord('a')] += 1
8 steps = 0
9 for i in range(26):
10 if count_t[i] < count_s[i]:
11 steps += count_s[i] - count_t[i]
12 return stepsℹ
Complexity note: The time complexity is linear because we only traverse each string once to count characters, making it efficient for large inputs.
- 1Character frequency is key to determining the number of replacements needed.
- 2Understanding how to compare character counts efficiently can save time.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.