Merge String Alternately
You are given two strings
word1andword2. Merge the strings by adding letters in alternating order, starting withword1. If a string is longer than the other, append the additional letters onto the end of the merged string.
JavaScript
My first thought was a try-catch to read an array then write a new string that failed when we ran out indexes, but using JavaScript, we don’t get an error. Instead of an error, we get an “undefined.” Rather than check for undefined, I used a couple ternary’s and only added to the new word if the index was in range.
/**
* @param {string} word1
* @param {string} word2
* @return {string}
*/
var mergeAlternately = function(word1, word2) {
let newWord = "";
let index = 0;
while ( index < word1.length || index < word2.length ){
newWord += index < word1.length ? word1[index] : "";
newWord += index < word2.length ? word2[index] : "";
index++;
}
return newWord;
};
Python
The comments on this LeetCode clued me in to the fact that strings are immutable in Python, and so using += to concatenate strings creates a new string each time. This is not very efficient, and so using join was the recommended solution. Additionally, python does fail when referencing an array index that doesn’t exist, so I implemented the try-catch (try-except) here. Also note, Python uses .append instead of .push for arrays. Here’s an example.
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
newWordArray = []
index = 0
moreWord1 = True
moreWord2 = True
while moreWord1 or moreWord2:
try:
newWordArray.append(word1[index])
except:
moreWord1 = False
try:
newWordArray.append(word2[index])
except:
moreWord2 = False
index += 1
return "".join(newWordArray)
