
Sponsored
Sponsored
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.
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.
1def minSteps(s: str, t: str) -> int:
2 count = [0] * 26
3 steps = 0
4
5 for c in s:
6 count[ord(c) - ord('a')] += 1
7
8 for c in t:
9 count[ord(c) - ord('a')] -= 1
10
11 for freq in count:
12 if freq > 0:
13 steps += freq
14
15 return steps
16
17print(minSteps("leetcode", "practice"))The Python function achieves the solution using a list to hold frequency counts. Characters in s increment counters, while those in t decrement, with a final loop to tally required changes.