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 <iostream>
2#include <string>
3
4std::string mergeAlternately(const std::string& word1, const std::string& word2) {
5 std::string result;
6 int i = 0, j = 0;
7 while (i < word1.size() && j < word2.size()) {
8 result += word1[i++];
9 result += word2[j++];
10 }
11 result += word1.substr(i);
12 result += word2.substr(j);
13 return result;
14}
15
16int main() {
17 std::string word1 = "abc";
18 std::string word2 = "pqr";
19 std::cout << mergeAlternately(word1, word2) << std::endl;
20 return 0;
21}
The function mergeAlternately
initializes index variables to add characters from each string alternately to a result string. After fully traversing the shorter string, it appends the remaining part of the longer string using substr
. The result string is then returned.
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.