Sponsored
Sponsored
This approach uses a loop to iterate through the characters in the strings by index. We initiate a loop for the length of the shorter string, adding characters alternately from each string to a result. Once the loop ends, we append the remaining part of the longer string.
Time Complexity: O(n + m), where n and m are the lengths of the two strings.
Space Complexity: O(n + m) for the resulting string.
1#include <stdio.h>
2#include <string.h>
3
4char* mergeAlternately(char* word1, char* word2) {
5 int len1 = strlen(word1);
6 int len2 = strlen(word2);
7 int maxLength = len1 + len2;
8 char* result = (char*)malloc((maxLength + 1) * sizeof(char));
9 int index = 0, i = 0, j = 0;
10
11 while (i < len1 && j < len2) {
12 result[index++] = word1[i++];
13 result[index++] = word2[j++];
14 }
15 while (i < len1) {
16 result[index++] = word1[i++];
17 }
18 while (j < len2) {
19 result[index++] = word2[j++];
20 }
21 result[index] = '\0';
22
23 return result;
24}
25
26int main() {
27 char word1[] = "abc";
28 char word2[] = "pqr";
29 char* merged = mergeAlternately(word1, word2);
30 printf("%s\n", merged);
31 free(merged);
32 return 0;
33}
The function mergeAlternately
initializes by determining the lengths of the input strings. It allocates memory for the result string that can accommodate both input strings' lengths combined. It uses two indices to add characters alternately from each input string. When one string ends, the remaining characters of the other string are appended to the result. Finally, the function returns the merged string.
This approach uses recursion to merge the strings by alternating characters. It utilizes recursive calls to handle the process of alternately taking characters from each string, ending the recursion once one of the strings is fully consumed. The remaining part of the longer string is then joined directly to the result.
Time Complexity: O(n + m), where n and m are the lengths of the two strings.
Space Complexity: O(n + m) for call stack and resulting string in the worst case.
1def merge_alternately(word1: str, word2: str) -> str:
2
This recursive function merge_alternately
checks if either string is empty. If so, it returns the remaining part of the other string. Otherwise, it returns the first character of each string concatenated with a recursive call using the rest of the strings.