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.
1def merge_alternately(word1: str, word2: str) -> str:
2 result = []
3 i, j = 0, 0
4 while i < len(word1) and j < len(word2):
5 result.append(word1[i])
6 result.append(word2[j])
7 i += 1
8 j += 1
9 result.append(word1[i:])
10 result.append(word2[j:])
11 return ''.join(result)
12
13print(merge_alternately("abc", "pqr"))
The function merge_alternately
merges the strings using two indices. It appends characters alternately to a list and concatenates remaining parts of the longer string if one finishes earlier. Finally, the merged result is constructed with join
.
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.