
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 <stdio.h>
2#include <string.h>
3
4int minSteps(char * s, char * t) {
5 int count[26] = {0};
6 int steps = 0;
7
8 // Count frequency of each character in s
9 for (int i = 0; s[i] != '\0'; i++) {
10 count[s[i] - 'a']++;
11 }
12
13 // Decrease the frequency according to characters in t
14 for (int i = 0; t[i] != '\0'; i++) {
15 count[t[i] - 'a']--;
16 }
17
18 // Count the number of steps required
19 for (int i = 0; i < 26; i++) {
20 if (count[i] > 0) {
21 steps += count[i];
22 }
23 }
24 return steps;
25}
26
27int main() {
28 char s[] = "leetcode";
29 char t[] = "practice";
30 printf("%d", minSteps(s, t));
31 return 0;
32}This C code defines a function that calculates the difference in frequency of each character between the two strings. It uses an array of size 26 to store the frequency count of characters. The function iterates through the string s to increment the frequency and then through t to decrement. The remaining positive values in the array represent the total change needed.