Dare2Solve
Given two strings, word1
and word2
, the task is to merge them alternately. The function should combine the two strings by adding one character from word1
followed by one character from word2
, continuing this process until one or both strings are exhausted. The remaining characters from the longer string, if any, are then appended to the end of the result.
The intuition behind this problem is straightforward. Since the goal is to merge two strings in an alternating fashion, we can iterate through both strings simultaneously, appending one character from each string to the result string. If one string is longer, we simply append the remaining characters from the longer string after the loop ends.
word1
, append the character from word1
.word2
, append the character from word2
.The time complexity is (O(\max(n, m))), where (n) is the length of word1
and (m) is the length of word2
. This is because the function iterates through both strings, processing each character once.
The space complexity is (O(n + m)), as the function creates a new string that contains all characters from both word1
and word2
.
class Solution {
public:
string mergeAlternately(string word1, string word2) {
string result = "";
int len1 = word1.length();
int len2 = word2.length();
for (int i = 0; i < max(len1, len2); i++) {
if (i < len1) result += word1[i];
if (i < len2) result += word2[i];
}
return result;
}
};
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
result = ""
len1, len2 = len(word1), len(word2)
for i in range(max(len1, len2)):
if i < len1:
result += word1[i]
if i < len2:
result += word2[i]
return result
class Solution {
public String mergeAlternately(String word1, String word2) {
StringBuilder result = new StringBuilder();
int len1 = word1.length();
int len2 = word2.length();
for (int i = 0; i < Math.max(len1, len2); i++) {
if (i < len1) result.append(word1.charAt(i));
if (i < len2) result.append(word2.charAt(i));
}
return result.toString();
}
}
var mergeAlternately = function (word1, word2) {
let result = '';
for (let i = 0; i < Math.max(word1.length, word2.length); i++) {
if (i < word1.length) result += word1[i];
if (i < word2.length) result += word2[i];
}
return result;
};