Approach
I know I must iterate over
the characters in the strings, but what do I iterate over? Word1? Word2? If one word is shorter than the other
(which is certainly possible, if not probable), we iterating over the smaller would miss some characters.
Alternatively,
we could find which word is longer and then set that as our loop.
Then, inside the for-loop, we can check
to see if index is less than the length of word1. If true, add the respective character at the index to the result.
Do the same with word2.
Note, we have to add word1's character before word2's per the instructions.
Complexity
Time
Complexity: O(n)
Space Complexity: O(len1+len2)
Code
class Solution { public: string mergeAlternately(string word1, string word2) { string result = ""; int len1 = word1.length(); int len2 = word2.length(); int max = len1; if(len2 > len1) max = len2; for(int i = 0; i < max; i++){ if(i < len1) { result += word1[i]; } if(i < len2) { result += word2[i]; } } return result; } };