
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.
1#include <iostream>
2#include <vector>
3
4int minSteps(std::string s, std::string t) {
5 std::vector<int> count(26, 0);
6 int steps = 0;
7
8 for (char c : s) {
9 count[c - 'a']++;
10 }
11
12 for (char c : t) {
13 count[c - 'a']--;
14 }
15
16 for (int freq : count) {
17 if (freq > 0) {
18 steps += freq;
19 }
20 }
21
22 return steps;
23}
24
25int main() {
26 std::string s = "leetcode";
27 std::string t = "practice";
28 std::cout << minSteps(s, t);
29 return 0;
30}The C++ solution similarly computes the frequency differences using a vector to hold character counts. It counts characters for s and then decrements for t, finally summing any positive differences.