
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.
1function minSteps(s, t) {
2 let count = new Array(26).fill(0);
3 let steps = 0;
4
5 for (let char of s) {
6 count[char.charCodeAt(0) - 97]++;
7 }
8
9 for (let char of t) {
10 count[char.charCodeAt(0) - 97]--;
11 }
12
13 for (let freq of count) {
14 if (freq > 0) {
15 steps += freq;
16 }
17 }
18
19 return steps;
20}
21
22console.log(minSteps("leetcode", "practice"));The JavaScript approach uses an array to store frequency differences, normalizing accesses through character codes from 'a', and compute required steps as any positive remaining counts.