1768. Merge Strings Alternately
Explanation
To solve this problem, we can iterate over both input strings simultaneously and merge them by adding letters in alternating order. We can keep track of the current index in both strings and append the characters to the result string accordingly. If one string is longer than the other, we can simply append the remaining characters to the result string.
Algorithmic Idea
- Initialize two pointers
i
andj
forword1
andword2
respectively. - Iterate over both strings and merge them by adding letters in alternating order.
- If one string is longer than the other, append the remaining characters to the result string.
- Return the merged string.
Time Complexity
The time complexity of this approach is O(n), where n is the maximum length of word1
and word2
.
Space Complexity
The space complexity is also O(n) since we are using a StringBuilder to store the merged string.
class Solution {
public String mergeAlternately(String word1, String word2) {
StringBuilder result = new StringBuilder();
int i = 0, j = 0;
while (i < word1.length() || j < word2.length()) {
if (i < word1.length()) {
result.append(word1.charAt(i));
i++;
}
if (j < word2.length()) {
result.append(word2.charAt(j));
j++;
}
}
return result.toString();
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.