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.
1public class MergeStrings {
2 public static String mergeAlternately(String word1, String word2) {
3 StringBuilder result = new StringBuilder();
4 int i = 0, j = 0;
5 while (i < word1.length() && j < word2.length()) {
6 result.append(word1.charAt(i++));
7 result.append(word2.charAt(j++));
8 }
9 result.append(word1.substring(i));
10 result.append(word2.substring(j));
11 return result.toString();
12 }
13
14 public static void main(String[] args) {
15 String word1 = "abc";
16 String word2 = "pqr";
17 System.out.println(mergeAlternately(word1, word2));
18 }
19}
The function mergeAlternately
uses a StringBuilder
to efficiently build the result string by iterating through the input strings. It alternates character addition from each input, appending the rest of the longer string at the end if there are any leftovers.
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.